0

I want to fork a child process that runs permanently in the background, and parent will prompt the user to enter a line of text. Then display the number of lines entered by the user in child process.

how to do it??

#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;
    }
}
Nelson Tang
  • 41
  • 1
  • 5
  • You need to create a pipe between the processes, but in the actual state of your code it's way to broad for a question. – Iharob Al Asimi Oct 10 '15 at 03:00
  • even with the current state of your program, there are many ways to pass information from one process to another process. May be you can take a look at IPC (inter process communication) mechanisms. – Pawan Oct 10 '15 at 04:07
  • have a look at answer section for this question in http://stackoverflow.com/questions/4812891/fork-and-pipes-in-c.it will help you. – BEPP Oct 10 '15 at 06:19
  • pipe() or socketpair() seem like obvious solutions, have a look at the linux programming guide. – Jasen Oct 10 '15 at 06:20

1 Answers1

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"); 
}
clearlight
  • 12,255
  • 11
  • 57
  • 75