c - 在 C 中报告退出状态时使用 execlp 和 execvp 的正确方法
问题描述
我是一名学习 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
为什么我错过了第二个出口打印?
解决方案
推荐阅读
- ios - AudioKit - 在没有操场的情况下绘制文件的完整波形
- javascript - JQuery data() 设置不持久
- io - Octave / CLI -- 在同一控制台线上保持长输出
- python - python注释中冒号包装的类是什么意思?
- .net-core - dotnet add package bootstrap 在源 nuget.org 中出现 404 错误
- php - 如何回显php输出?(呼应 HTML 作品)
- aws-lambda - 多功能SAM模板推荐项目结构
- jenkins - Jenkins Pipeline:查看子构建作业的日志
- python - Python 与 C 中的每行多个属性
- firebase - 在 Firebase 中查询相关项目