Fork()

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

int main(){
    fork();
    fork();
    fork();

    sleep(30);
    
}

Screen Shot 2022-02-21 at 10.44.17 PM.png


Parent and Child

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

int main(){
    pid_t ret_value;
    printf("\\nThe process id is %d\\n",getpid());

    ret_value = fork();

    if (ret_value < 0){
        printf("\\nfork() Gagal\\n");
    }

    else if (ret_value == 0){
        printf("\\nChild process id is %d\\n",getpid());
        sleep(20);
    }

    else{
				wait();
        printf("\\nParent process id is %d\\n",getpid());
        sleep(30);
    }

return 0;
}

// check zombie by using ps -al
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(){
    pid_t pid;
    pid = fork();
    if(pid < 0){
        fprintf(stderr, "fork failed\\n");
        return 1;
    }

    else if (pid == 0){
        // execlp("/bin/ls","ls",NULL);
        printf("hello, I am child: (pid:%d)\\n", (int) getpid());
        sleep(40);
    }

    else {
        printf("hello, I am parent: (pid:%d)\\n", (int) getpid());
        wait(NULL);
        printf("Child Complete");
    }

    return 0;
}

ps(1) - Linux manual page


Exec()

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

int main(int argc, char *argv[]){
    printf("Hello, We are in EX1 with PID: %d\\n", getpid());
    char *args[] = {NULL};

    execv("./ex2", args);
    printf("We are back to EX1\\n");
    return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
    printf("We are in EX2\\n");
    char *args[] = {NULL};
    printf("PID of ex2: %d\\n", getpid());
    execv("./ex1", args);
    return 0;   
}