COMS 3157 Advanced Programming

Index of 2024-9/code/15

Parent directory
ap-shell.c
parent-child.c

ap-shell.c

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

static void die(const char *s) { perror(s); exit(1); }

int main()
{
    char	buf[100];
    pid_t	pid;
    int		status;

    printf("AP> ");
    while (fgets(buf, sizeof(buf), stdin) != NULL) {

        if (buf[strlen(buf) - 1] == '\n') {
            buf[strlen(buf) - 1] = 0; // replace newline with '\0'
        }

        pid = fork();

        if (pid < 0) {
            die("fork error");

        } else if (pid == 0) { // child process

            char *argv[] = { buf, NULL };
            execv(argv[0], argv);

            // or alternatively:
            // execl(buf, buf, (char *)0);

            die("execl failed");

        } else { // parent process

            if (waitpid(pid, &status, 0) != pid) {
                die("waitpid failed");
            }
        }
        printf("AP> ");
    }
}

parent-child.c

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

int main()
{
    int i;
    pid_t p;

    p = fork();

    if (p > 0) {
        for (i = 0; i < 10; i++) {
            printf("Listen to me\n");
            sleep(1);
        }
        printf("I give up...\n");
        return 0;
    }
    else if (p == 0) {
        for (i = 0; i < 10; i++) {
            printf("No way\n");
            sleep(1);
        }
        printf("Whatever.\n");
        return 1;
    }
    else {
        perror("fork failed");
        return -1;
    }
}