我想這樣做2個子進程將把他們的名字,並等待,直到其他進程把他的名字。例如,如果有第一個和第二個過程,首先將她的名字放在屏幕上等待他人的名字。所以我想和流程一起工作,我希望看到他們正在順序地工作。c管道流程如何順序工作
輸出:
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。
您可能想要考慮** parallel **執行的含義。搜索「進程同步」。順便說一句:你的問題是什麼? – Olaf
這不是你的真實產出。我知道這是因爲你的程序也輸出了'a'的值。發佈您的真實輸出(或其中的一小部分)... – immibis