|
CS471/571 - Operating Systems
|
Displaying ./code/System-calls/fork-exec.c
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
/**
* Forks a new process and execs the command: ps a u
*/
int main(void)
{
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
} else if (pid == 0) {
// Redirect output to the file "output"
close(STDOUT_FILENO);
open("output", O_WRONLY | O_CREAT | O_TRUNC, 0666);
// The child process
execlp("ps", "ps", "a", "u", NULL);
perror("exec");
return 1;
} else {
// The parent process
int status;
wait(&status);
printf("Child has exited with status = %d\n", WEXITSTATUS(status));
}
return 0;
}
|