fork - hochan222/Everything-in-JavaScript GitHub Wiki

๋ฆฌ๋ˆ…์Šค ์‹œ์Šคํ…œ์—์„œ๋Š” ํ”„๋กœ์„ธ์Šค๋ฅผ ์ƒ์„ฑํ•˜๋Š” system call์ธ fork, vfork ํ•จ์ˆ˜๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. fork์™€ vfork๋Š” ํ”„๋กœ์„ธ์Šค ์ž์‹ ์˜ ํ”„๋กœ๊ทธ๋žจ ์ด๋ฏธ์ง€๋ฅผ ๋น„๋กฏํ•˜์—ฌ ๋งŽ์€ ์ •๋ณด๋ฅผ ๋ณต์ œํ•œ ์ž์‹ ํ”„๋กœ์„ธ์Šค๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

//fork() ํ•จ์ˆ˜.
//Parent Process, Child Process์— ๊ด€ํ•œ ์˜ˆ์ œ.

#include <stdio.h>
#include <unistd.h> // pid_t ํƒ€์ž…, fork() ํ•จ์ˆ˜๊ฐ€ ํฌํ•จ๋œ ํ—ค๋”

int main()
{ 
  pid_t pid; // pid_t ํƒ€์ž…์€ ํ”„๋กœ์„ธ์Šค์•„์ด๋””(PID)๋ฅผ ์ €์žฅํ•˜๋Š” ํƒ€์ž….

  /* fork another process */ pid = fork(); // fork() ํ•จ์ˆ˜๋Š” ํ˜„์žฌ ์‹คํ–‰์ค‘์ธ ํ”„๋กœ์„ธ์Šค๋ฅผ ๋ณต์‚ฌํ•˜์—ฌ ์‹คํ–‰ํ•œ๋‹ค.

  if (pid < 0) { /* error occurred */

  // pid๊ฐ€ ์Œ์ˆ˜์ผ ๊ฒฝ์šฐ๋Š” fork() ์‹คํŒจ. 
    fprintf(stderr, "Fork Failed"); 
    exit(-1); 
  } else if (pid == 0) { 
  /* child process */

  // Child Process๋Š” pid๋กœ 0์„ ๋ฆฌํ„ด. 
    printf("Child Process is running\n"); 
    sleep (10); 
    execlp("/bin/ls", "ls", NULL); // ์•„๋ž˜์—์„œ ์„ค๋ช…. 
  } else { 
  /* parent process */ 

  /* parent will wait for the child to complete */ 
  wait (NULL);

  /* wait()์˜ ํ”„๋กœํ† ํƒ€์ž…์€ pid_t wait(int* status)์ด๋‹ค.
  status๋Š” Child Process ์ข…๋ฃŒ ์‹œ์˜ ์ƒํƒœ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๊ณ ,
  ๋ฆฌํ„ด๊ฐ’์ธ pid_t๋Š” ์ข…๋ฃŒ๋œ Child Process์˜ PID๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.
  Child Process๊ฐ€ ์ข…๋ฃŒ๋œ ํ›„์— Parent Process๊ฐ€ ์‹คํ–‰๋œ๋‹ค. */ 
    printf ("Child Complete\n"); 
    exit(0); // ์‹คํ–‰๋œ Parent Process์˜ ๋‚˜๋จธ์ง€ ๋ถ€๋ถ„. 
  }
}

์ž์‹ ํ”„๋กœ์„ธ์Šค์—๊ฒŒ pid๋ฅผ 0์„ ์ฃผ๋Š” ์ด์œ ๋Š” ์ž์‹ ํ”„๋กœ์„ธ์Šค์—์„œ๋Š” ํ•„์š”ํ•˜๋ฉด getppid ์‹œ์Šคํ…œ ํ˜ธ์ถœ๋กœ ๋ถ€๋ชจ ํ”„๋กœ์„ธ์Šค์˜ pid๋ฅผ ์•Œ์•„๋‚ผ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ถ€๋ชจ ํ”„๋กœ์„ธ์Šค์—์„œ๋Š” ์ž์‹ ํ”„๋กœ์„ธ์Šค์˜ pid๋ฅผ ์•Œ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์€ fork์™€ vfork์— ์˜ํ•ด ๋ฐ˜ํ™˜ํ•˜๋Š” pid๋ฅผ ๊ธฐ์–ตํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.


WIFEXITED, WEXITSTATUS

WIFEXITED : ์ž์‹ ํ”„๋กœ์„ธ์Šค๊ฐ€ ์ •์ƒ ์ข…๋ฃŒํ•œ ๊ฒฝ์šฐ TRUE๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
WEXITSTATUS : ์ž์‹ ํ”„๋กœ์„ธ์Šค์˜ ์ „๋‹ฌ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

capturing-exit-status-code-of-child-process

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

int main(void)
{
    pid_t p = fork();
    if ( p == -1 ) {
        perror("fork failed");
        return EXIT_FAILURE;
    }
    else if ( p == 0 ) {
        execl("/bin/sh", "bin/sh", "-c", "./failprog", "NULL");
        return EXIT_FAILURE;
    }

    int status;
    if ( waitpid(p, &status, 0) == -1 ) {
        perror("waitpid failed");
        return EXIT_FAILURE;
    }

    if ( WIFEXITED(status) ) {
        const int es = WEXITSTATUS(status);
        printf("exit status was %d\n", es);
    }

    return EXIT_SUCCESS;
}
โš ๏ธ **GitHub.com Fallback** โš ๏ธ