gpt4 book ai didi

c - APUE :how to print something alternately in two process?

转载 作者:行者123 更新时间:2023-11-30 15:54:58 25 4
gpt4 key购买 nike

#include<apue.h>
#include<signal.h>

static void charatatime(char *str)
{
char *ptr;
int c;
setbuf(stdout,NULL);
for (ptr = str;(c = *ptr++) != 0;)
putc(c,stdout);
}

int main(int argc , char *argv[])
{
pid_t pid;
int i;
TELL_WAIT();

if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0)
{

for (i = 0;i < 10;++i)
{
WAIT_PARENT();
charatatime("ouput from child\n");
}

exit(0);
}
else
{

for (i = 0;i < 10;++i)
{
charatatime("output from parent\n");
TELL_CHILD(pid);
}
}
return 0;
}

它只打印两次而没有任何循环就可以正常工作。但是当我尝试使用 for 循环打印更多次......我认为父进程应该在 TELL_CHILD(pid) 完成后等待子进程......

最佳答案

您的问题是,在写入后,父级不会等待子级接管。因此,您的代码仅确保子级在父级至少写入一次后才会写入。

我无法测试代码,因此请检查错误,但也许这样的东西会起作用:

#include<apue.h>
#include<signal.h>

static void charatatime(char *str)
{
char *ptr;
int c;
setbuf(stdout,NULL);
for (ptr = str;(c = *ptr++) != 0;)
putc(c,stdout);
}

int main(int argc , char *argv[])
{
pid_t pid;
int i;
TELL_WAIT();

if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0)
{
TELL_PARENT();

for (i = 0;i < 10;++i)
{
WAIT_PARENT();
charatatime("ouput from child\n");
TELL_PARENT();
}

exit(0);
}
else
{

for (i = 0;i < 10;++i)
{
WAIT_CHILD(pid);
charatatime("output from parent\n");
TELL_CHILD(pid);
}
}
return 0;
}

关于c - APUE :how to print something alternately in two process?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12623022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com