2012. 7. 13. 16:40

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
   pid_t childpid = 0;
   int i, n;

   if (argc != 2){   /* check for valid number of command-line arguments */
      fprintf(stderr, "Usage: %s processes\n", argv[0]);
      return 1;
   }    
   n = atoi(argv[1]);  
   for (i = 1; i < n; i++)
      if (childpid = fork())
         break;

   fprintf(stderr, "i:%d  process ID:%ld  parent ID:%ld  child ID:%ld\n",
           i, (long)getpid(), (long)getppid(), (long)childpid);
   return 0;
}


[root@emb27 chain_p]# ./chain 4
i:4  process ID:18663  parent ID:18662  child ID:0
i:3  process ID:18662  parent ID:18661  child ID:18663
i:2  process ID:18661  parent ID:18660  child ID:18662
i:1  process ID:18660  parent ID:18375  child ID:18661
[root@emb27 chain_p]#



--------------------------------------------------------------------------------------------------------------------------------
루프에서 fork함수를 호출하여 n개의 프로세스팬을 생성한다. 새롭게 생성된 자식 프로세스는 루프를 빠져나가고 부모 프로세스는 루프 내에서 계속 실행된다

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
   pid_t childpid = 0;
   int i, n;

   if (argc != 2){   /* check for valid number of command-line arguments */
      fprintf(stderr, "Usage: %s processes\n", argv[0]);
      return 1;
   }    
   n = atoi(argv[1]);  
   for (i = 1; i < n; i++)
      if ((childpid = fork()) <= 0)
         break;

   fprintf(stderr, "i:%d  process ID:%ld  parent ID:%ld  child ID:%ld\n",
           i, (long)getpid(), (long)getppid(), (long)childpid);
   return 0;
}

i:1  process ID:18728  parent ID:18727  child ID:0
i:2  process ID:18729  parent ID:18727  child ID:0
i:3  process ID:18730  parent ID:18727  child ID:0
i:4  process ID:18727  parent ID:18375  child ID:18730
[root@emb27 chain_p]# ./chain2 3
i:1  process ID:18732  parent ID:18731  child ID:0
i:2  process ID:18733  parent ID:18731  child ID:0
i:3  process ID:18731  parent ID:18375  child ID:18733
[root@emb27 chain_p]#

Posted by 몰라욧