2014년 11월 6일 목요일

Fork & Execv

Below code is simple fork & execv code for system programming

The sender generate a thread to print "I run".

After sender generate the thread,

it just prints out the PID of the thread.

Receiver is the thread.

 
//Receiver

#include <stdio.h>

#define DIE(x) perror(x), exit(1)

int main(int argc, char **argv)
{
printf("I run %s\n", argv[1]);

return 0;
}


 
//Sender

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

int main()
{
int status;
pid_t pid;
char *argv[3];

argv[0] = "test1";
argv[1] = "boot";
argv[2] = NULL;

switch(pid=fork())
{
case -1: // Error
perror("fork");
exit(1);
break;
case 0: // child
printf("%d\n", (int)getpid());
execv("test1", argv);
exit(0);
break;
default:
while(wait(&status) != pid)
continue;
printf("%d\n", (int)getpid());
break;
}

return 0;
}

 

[contact-form-7 id="24" title="Karl"]

댓글 없음:

댓글 쓰기