summaryrefslogtreecommitdiff
path: root/examples/execve.c
blob: fd7d2e71c41d361a9173813cc0f28a752dcdcd4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>

int main(void) {
    printf("Main program started\n");

    int pid = vfork();
    if (pid == -1) {
        printf("failed to fork - %d", errno);
        return 1;
    }

    if (pid == 0) {
        printf("execve: echo hi-from-child\n");
        char* argv[] = { "echo", "hi-from-child", NULL };
        char* envp[] = { NULL };
        if (execve("/bin/echo", argv, envp) == -1) {
            perror("Could not execve");
        }
    } else {
        int status = 0;
        waitpid(pid, &status, 0);
        fprintf(stderr, "Child(%d) exited with %d\n", pid, status);

        fprintf(stderr, "execve: echo hi-from-parent\n");
        char* argv[] = { "echo", "hi-from-parent", NULL };
        char* envp[] = { NULL };
        if (execve("/bin/echo", argv, envp) == -1) {
            perror("Could not execve");
        }
    }

    return 1;
}