[英]Proper way to use execlp and execvp while reporting exit status in C
我是一名学习 C 以及如何使用 fork() 创建进程的学生,您能否解释一下这两个代码之间的区别,因为我已经尝试了这两个代码,但它们没有按预期工作。
child = fork();
child1 = fork();
if (child == 0 && child1 == 0){//Parent}
else if (child > 0 && child1 == 0){//first child}
else if (child == 0 && child1 > 0){//second child}
else {third child}
这是创建孩子的正确方法还是下面的方法?
child = fork();
if (child == 0)
{
child1 = fork();
if (child1 == 0)
{// grandchild
}
else
{//child
}
}
else
{//parent
}
这些是我写的关于让我困惑的例子。 这是我遇到问题的代码
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char ** argv)
{
pid_t child;
pid_t child1;
// at least, there should be 3 arguments
// 2 for the first command, and the rest for the second command
//printf("%d\n", argc);
if (argc < 4) {
fprintf(stderr, "Usage: %s cmd1 cmd1_arg cmd2 [cmd2_args ..]\n", argv[0]);
return 1;
}
child = fork();
//pid_t child1;
// TODO
if (child < 0)
{
perror("fork()");
exit(EXIT_FAILURE);
}
if (child == 0)//child1
{
//printf("exited=%d exitstatus=%d\n", WIFEXITED(exitStatus), WEXITSTATUS(exitStatus));
child1 = fork();
if (child1 == 0)//grandchild
{
execlp(argv[1],argv[1],argv[2],NULL);
perror("execlp()");
exit(EXIT_FAILURE);
}
else //first child
{
int status1;
waitpid(child1, &status1, 0);
printf("exited=%d exitstatus=%d\n", WIFEXITED(status1), WEXITSTATUS(status1));
execvp(argv[3], (argv + 3));
perror("execlp()");
exit(EXIT_FAILURE);
}
}
else//parent
{
int status;
waitpid(child, &status, 0);
printf("exited=%d exitstatus=%d\n", WIFEXITED(status), WEXITSTATUS(status));
}
return 0;
}
我能够让代码按预期工作,但我对如何使用 WIFEXITED 和 WEXITSTATUS 感到困惑。 我运行此代码时的代码输出是
execlp(): No such file or directory
Makefile
exited=1 exitstatus=0
正确的输出是:
execlp(): No such file or directory
Makefile
exited=1 exitstatus=1
exited=1 exitstatus=0
此测试用例中使用的参数
cal -3 ls Makefile
为什么我错过了第二个出口打印?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.