我想分叉在后台永久运行的子进程,父进程将提示用户输入一行文本。然后显示用户在子进程中输入的行数。
怎么做?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
int main ( int argc, char *argv[] )
{
pid_t pid;
int mypipe[2];
int ret;
char str[5000];
char buff[2000];
int status = 0;
int lines = 1;
int c = 0;
int line[1000];
ret = pipe(mypipe);
if (ret == -1)
{
perror("pipe");
exit(1);
}
pid = fork();
if (pid == -1)
{
perror("fork");
exit(1);
}
else if (pid == 0)
{
read(mypipe[0],line,50);
printf("Child count line : %d\n", line[0]);
}
else
{
//in parent process
printf("In Parent Process\n");
printf("Enter somthing: \n");
while ((c =getchar())!= '*'){
if (c == '\n'){
lines++;
}
line[0] = lines;
write(mypipe[1],line,sizeof(int));
}
wait(&status);
}
}
理想输出应如下所示:
ds
Child count line : 1
sd
Child count line : 2
sd
Child count line : 3
sd
Child count line : 4