分叉子进程,在后台永久运行并运行

时间:2015-10-10 02:59:22

标签: c fork parent

我想分叉在后台永久运行的子进程,父进程将提示用户输入一行文本。然后显示用户在子进程中输入的行数。

怎么做?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

int main ( int argc, char *argv[] )
{
     int i, pid, status;
     pid = fork();

     switch(pid){
        case -1: printf("fork error");
        break;
        case 0: printf("In child with pid %d\n", (int)getpid());
        // print out the number of lines on screen
        while(1);
        break;
        default: printf("In parents with pid %d\n", (int)getpid());
        printf("\nPlease Enter somthing...\n");
        // Maybe do counting here? and send it over the child?
        wait(&status);
        break;
    }
}

1 个答案:

答案 0 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

void do_parent();
void do_child();

int fd[2] = { 0 };

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

     if (pipe(fd) < 0) {
        fprintf(stderr, "Error opening pipe\n");
        exit(-1);
     }
     switch(pid = fork()) {
        case -1: 
            fprintf(stderr, "fork error\n");
            exit(-1);
        case 0: 
            do_child();
            fprintf(stderr, "child exited\n");
            exit(0);
        default:
            do_parent(pid);
            fprintf(stderr, "parent exited\n");
            exit(0);
     }
}

void
do_parent(int child_pid) 
{

    printf("parent pid: %d, child's pid: %d\n", getpid(), child_pid);
    dup2(fd[0], 0);
    char buf[256];
    while(gets(buf) != NULL && strncmp(buf, "done", 4) != 0)
        printf("parent received: %s\n", buf);
    printf("nothing left from child\n");
}

void
do_child() 
{
    dup2(fd[1], 1);
    for (int i = 0; i < 100; i++)
        printf("child iteration #%d\n", i);
    printf("done\n"); 
}