Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

9/16/2013

Linux system calls - fork,exec and pipes.

These days I am passionate about network programming concepts, in order to fully understand Nodejs stack.
I created a small program to demonstrate canonical usage of basic linux system calls - fork, exec and pipes. These calls are used in most network applications and servers. It is heavily commented. Sorry for the code formatting, it is syntax highlighter issue.

#include
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


// canonical example of fork,pipe and exec.
// it is heavily commented

// main program
int main (int argc, char ** args)
{
    // pipe
    int p[2];
    char buf[5]="\0";
    int pid;

    // do we have a fork ?
    if (!fork()){
        // write to one end of pipe
        write(p[1],"Child writes to pipe\n",22);

        // open a file
        int fd = open("one.js",O_RDWR);
        // read from that file
        read(fd,buf,70);

        //close file descriptor
        close(1);
        // replicate closed descriptro
        int i = dup(0);
        // print usefull message
        printf("Value of fd is: %d\n",i);

        // open new program, and provide some arguments
        execlp("./one","one",buf,NULL);

        // don't forget to exit child process and close open file descriptor
        exit(0);
        close(fd);
    }else{
        printf("Parent reading pipe");
        // read from a pipe
        read(p[0],buf,5);
        // print a pipe content
        printf("%s\n",buf);
        // wait for a child to exit
        wait(NULL);
    }
   return 0;
}
//

Thanx for visiting my blog
Happy Coding :)

No comments:

Post a Comment