【发布时间】:2015-11-18 00:00:58
【问题描述】:
我想这样做 2 个子进程将输入他们的名字并等到其他进程输入他的名字。例如,如果有第一个和第二个进程,第一个将把她的名字放在屏幕上等待其他人的名字。所以我想处理流程,我想看到它们是按顺序工作的。
输出:
first
second
first
second
first
second
我刚刚尝试了一些关于 C(linux) 的东西。
int main(void)
{
pid_t child_a, child_b;
int pipe1[2], pipe2[2];
char mesazhi1[] = "first";
char mesazhi2[] = "second";
char buf[1024];
int first_pipe = pipe(pipe1);
pipe(pipe2);
if(first_pipe == -1){
perror("pipe");
exit(1);
}
child_a = fork();
if (child_a == 0)
{
/* Child A code */
int i;
for (i = 0; i < 3; i++)
{
write(pipe1[1],mesazhi1, strlen(mesazhi1) + 1);
//printf("first\n");
int a = read(pipe2[0], buf, strlen(mesazhi2) + 1);
printf("%s - %d\n", buf, a);
}
}
else
{
child_b = fork();
if (child_b == 0)
{
int i;
for (i = 0; i < 3; i++)
{
write(pipe2[1],mesazhi2, strlen(mesazhi2) + 1);
//printf("second\n");
int a = read(pipe1[0], buf, strlen(mesazhi1) + 1);
printf("%s - %d\n", buf, a);
}
}
else
{
/* Parent Code */
int returnStatusA,returnStatusB;
waitpid(child_a, &returnStatusA, 0); // Parent process waits here for child to terminate.
waitpid(child_b, &returnStatusB, 0); // Parent process waits here for child to terminate.
if (returnStatusA == 0 && returnStatusB == 0) // Verify child process terminated without error.
{
printf("%s\n", "The child processes terminated normally.\n");
}
if (returnStatusA == 1 && returnStatusB == 1)
{
printf("%s\n", "The child processes terminated with an error!. \n" );
}
}
}
}
它是随机输入名称。我的意思是我认为,有时第二个过程比第一个过程更快。这样的输出:
first
second
second
first
second
...
那么为什么第二个进程不等待第一个,因为我认为 read() 函数应该等到 pipe1 中有东西。
【问题讨论】:
-
您可能需要考虑并行执行的含义。搜索“进程同步”。顺便说一句:你的问题是什么?
-
这不是你真正的输出。我知道这是因为您的程序也打印了
a的值。发布您的真实输出(或其中的一小部分)...