【发布时间】:2017-02-27 10:59:35
【问题描述】:
wait()、exit() 和信号被禁止 只允许使用管道 用户给出一个整数正数-N 并创建 N 个进程,父亲创建一个孩子,该孩子成为父亲并创建另一个孩子,依此类推。第一个进程(N-1)中的每一个都应该先等待完成它的子进程,然后再等待它自己。初始进程应打印“1-我的进程 ID:”,下一个创建的进程应打印“2 我的进程 ID:和我父亲的 ID:”等。 我的代码。我没有等待或退出,而是使用返回(-1)。 但我没有设法相应地打印数字1 我的进程 ID...、2 我的进程 ID...、3 我的进程 ID...等等。n。 有什么想法吗?
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
/* Read characters from the pipe and echo them to stdout. */
void read_from_pipe (int file)
{
FILE *stream;
int c;
stream = fdopen (file, "r");
while ((c = fgetc (stream)) != EOF)
putchar (c);
fclose (stream);
}
/* Write some random text to the pipe. */
void write_to_pipe (int file)
{
FILE *stream;
stream = fdopen (file, "w");
fprintf (stream, "\n");
fprintf (stream, " ");
fclose (stream);
}
int main (void)
{
pid_t pid;
int mypipe[2];
int j = 1;
int i;
cout << "\nassume father is by default the first process\n" << "Please enter how child-processes you want: ";
cin >> i;
for( ; j < i; j++)
{
/* Create the pipe. */
if (pipe (mypipe))
{
fprintf (stderr, "Pipe failed.\n");
return (-1);
}
/* Create the child process. */
pid = fork ();
if (pid == (pid_t) 0)
{
/* This is the child process. Close other end first. */
pid = getpid();
close (mypipe[1]);
read_from_pipe (mypipe[0]);
printf("Child's ID: %d\n",pid);
sleep(0);
}
else if (pid > (pid_t) 0)
{
/* This is the parent process. Close other end first. */
pid = getpid();
close (mypipe[0]);
write_to_pipe (mypipe[1]);
printf("Dad's ID: %d\n",pid);
sleep(0);
}
else
{
/* The fork failed. */
fprintf (stderr, "Fork failed.\n");
return (-1);
}
}//end for
//close (mypipe[0]);
//write_to_pipe (mypipe[1]);
// printf("Dad's ID: %d\n",pid);
return (-1);
}// EOP
【问题讨论】:
标签: c++ unix process pipe fork