C Pthreads - 父/子

标签 c fork parent-child

我目前正在编写一个创建子进程的 C 程序。创建子进程后,父进程应该输出两条消息。第一个是“我是 parent ”,第二个是“ parent 已经完成”。对于子进程“我是 child ”和“ child 已经完成”也应该发生同样的情况。但是我想确保, child 的第二条消息总是在 parent 的第二条消息之前完成。我怎样才能实现这一点,以便打印“ child 完成”和“ parent 完成”而不是打印他们的 pid?

这是我目前拥有的:

#include <unistd.h>
#include <stdio.h>

main()
{
int pid, stat_loc;


printf("\nmy pid = %d\n", getpid());
pid = fork();

if (pid == -1)
perror("error in fork");

else if (pid ==0 )
{ 
   printf("\nI am the child process, my pid = %d\n\n", getpid());


} 
else  
{
  printf("\nI am the parent process, my pid = %d\n\n", getpid());       
  sleep(2);
}  
printf("\nThe %d is done\n\n", getpid());
}

最佳答案

如果你想先执行child,然后执行parents,那么你应该在parents中使用wait(),在child中使用exit()

使用 exit() 将子级 status 发送给父级。

int main() {
        int pid, stat_loc;
        printf("\nmy pid = %d\n", getpid());
        pid = fork();

        if (pid == -1) {
                perror("error in fork");
                return 0;
        }
        else if (pid ==0 ) {
                printf("\nI am the child process, my pid = %d\n\n", getpid());
                sleep(5);
                exit(0);/* sending child status */
        }
        else {
                int status = 0;
                int ret = wait(&status);/* wait() returns pid of the child for which its waiting */
                printf("\nThe %d is done\n\n", ret);
                printf("\nI am the parent process, my pid = %d\n\n", getpid());  
        }
        printf("\nThe %d is done\n\n", getpid());/* getpid() returns pid of the process */
        return 0;
}

关于C Pthreads - 父/子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48733293/

相关文章:

python - 通过名称从其父级访问 Gtk3 小部件

elasticsearch - 当在Elasticsearch中建立索引时如何在子文档上添加时间戳

android - 将字符串从子选项卡 Activity 传递到父选项卡

c++ - 如何将 C++ 回调传递给 C 库函数?

使用 fork() 和 exec() 在终端中创建新命令

c - 根据面积对n个三角形的边进行排序

c - WC 没有执行任何操作

隐式执行的 C fork 系统调用

C 根据真值表进行位运算

c - ssh使用expect登录使用c直接登录