c - Fork a child process,runs permanently in the background and do work -
i want fork child process runs permanently in background, , parent prompt user enter line of text. display number of lines entered user in child process.
how 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 pid %d\n", (int)getpid()); // print out number of lines on screen while(1); break; default: printf("in parents pid %d\n", (int)getpid()); printf("\nplease enter somthing...\n"); // maybe counting here? , send on child? wait(&status); break; } }
#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 child\n"); } void do_child() { dup2(fd[1], 1); (int = 0; < 100; i++) printf("child iteration #%d\n", i); printf("done\n"); }
Comments
Post a Comment