fork() 예제 : 자식 프로세스 생성

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

int main() {
    printf("hello world (pid:%d)\n", getpid());

    int rc = fork();  // 자식 프로세스 생성(성공하면 0 (자식에서) 반환, 실패하면 -1 반환)

    if (rc < 0) { 
        // fork 실패
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) {
        // 자식 프로세스
        printf("hello, I am child (pid:%d)\n", getpid());
    } else {
        // 부모 프로세스
        printf("hello, I am parent of %d (pid:%d)\n", rc, getpid());
    }

    return 0;
}
//결과 1
hello world (pid:1001)
hello, I am child (pid:1002)
hello, I am parent of 1002 (pid:1001)

//결과 2
hello world (pid:1001)
hello, I am parent of 1002 (pid:1001)
hello, I am child (pid:1002)
//비결정적 : 정해지지 않음

wait() 예제 : 자식 종료 대기

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

int main() {
    printf("hello world (pid:%d)\n", getpid());

    int rc = fork();

    if (rc < 0) {
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) {
        // 자식 프로세스
        printf("hello, I am child (pid:%d)\n", getpid());
    } else {
        // 부모 프로세스는 자식 종료까지 대기
        int wc = wait(NULL);
        printf("hello, I am parent of %d (wc:%d) (pid:%d)\n", rc, wc, getpid());
    }

    return 0;
}
//결과
hello world (pid:2001) //부모
hello, I am child (pid:2002) //자식
hello, I am parent of 2002 (wc:2002) (pid:2001) //부모

//결정적 : 정해진 결과나 나옴

exec() 예제 : 새 프로그램 실행

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

int main() {
    printf("hello world (pid:%d)\n", getpid());

    int rc = fork();

    if (rc == 0) {
        // 자식 프로세스: exec로 다른 프로그램 실행
        printf("hello, I am child (pid:%d)\n", getpid());

        char *myargs[3];
        myargs[0] = strdup("wc");     // 실행할 프로그램
        myargs[1] = strdup("p3.c");   // 인자 (파일명)
        myargs[2] = NULL;             // 인자 종료 표시

        execvp(myargs[0], myargs);    // "wc p3.c" 실행
        printf("this shouldn't print out\n"); // exec 성공 시 이 줄은 실행되지 않음
    } else {
        wait(NULL);  // 부모는 자식 종료까지 대기
        printf("hello, I am parent (pid:%d)\n", getpid());
    }

    return 0;
}
hello world (pid:3001) //부모
hello, I am child (pid:3002) //자식
29 107 1030 p3.c //자식에 있는 내용 출력
hello, I am parent of 3002 (wc:3002) (pid:3001) //자식이 종료된 후 부모 시행

✅ 프로그램 내 리디렉션 구현 (Redirection in C)

📌 목표

자식 프로세스에서 wc p4.c 명령을 실행하고, 그 출력 결과를 p4.output 파일로 저장하는 것