c - 为什么我的父进程没有等待第二次? C/Unix

标签 c unix

所以,我想做的是创建一个子进程,让它执行 execl 并运行 ls。然后在 ls 完成后,创建另一个子进程并让它在文件上运行 cat 命令。第二个 wait(pid) 似乎没有等待第二个子进程完成才完成。这是我的代码和输出

#include <fcntl.h>

int main(){
int pid;
printf("In parent process, creating child now...\n");
pid = fork();
if (pid==0){
 printf("Now in child process...\n");
 execl("/bin/ls","ls","-l",(char*)0);
}
wait(pid);
printf("ls child process complete\n");
printf("in parent process\n");
printf("Creating another child process\n");
pid=fork();
if(pid==0){
  execl("/bin/cat","cat","f1",(char*)0);
}
wait(pid);
return 0;

}

这是我的输出

In parent process, creating child now...
Now in child process...
"Contents of ls"
ls child process complete
in parent process
creating another child process
[username@host ~]$ "Contents of file" *cursor*

父进程似乎在第二个子进程完成之前就结束了。一次只有 1 个 child 。 “文件内容”应该出现在 [username@host ~]$ 提示符之前。我想我放错了等待或错误的 pid 分配或其他东西。提前致谢!

最佳答案

wait() 的参数不是 PID。它是指向将存储退出状态的 int 的指针。您在需要指针的地方传递了一个整数,这意味着:

  1. 一旦您调用 wait,程序可能会崩溃或损坏一些不相关的内存位置。它在那之后的行为是不可预测的。
  2. 您需要启用更多的编译器警告并注意它们。

关于c - 为什么我的父进程没有等待第二次? C/Unix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26898640/

相关文章:

c - 从函数地址获取调用者函数名称

c++ - 读取由换行符分隔的文本文件。 Unix 上的 C++

UNIX 中的 java.lang.NoClassDefFoundError

c - 我无法在 C 中获取 char 数组的值

c++ - 谁定义了 C 运算符优先级和关联性?

c - while 循环中的 if 和 else if 条件

unix - 确定文本文件中唯一性和重复性的最佳方法

具有文本格式化和上下文感知功能的 C 编辑器

linux - 如何使用不同的用户名和密码测试与多个服务器的 sftp 连接?

linux - 在 jar 中查找特定路径