Simple Fork()/execvp()/waitpid() Example
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#define EXEC_FAILED 1
int main(int argc, char *argv[])
{
int status;
int pid;
char *prog_arv[4];
/*
* Build argument list
*/
/* Remove the path or make the path correct for your system, as needed */
prog_argv[0] = "/usr/local/bin/ls";
prog_argv[1] = "-l";
prog_argv[2] = "/";
prog_argv[3] = NULL;
/*
* Create a process space for the ls
*/
if ((pid=fork()) < 0)
{
perror ("Fork failed");
exit(errno);
}
if (!pid)
{
/* This is the child, so execute the ls */
execvp (prog_argv[0], prog_argv);
exit(EXEC_FAILED);
}
if (pid)
{
/*
* We're in the parent; let's wait for the child to finish
*/
waitpid (pid, NULL, 0); /* Could also be wait(NULL); */
}
}
Simple Fork()/execlp()/wait() Example
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#define EXEC_FAILED 1
int main(int argc, char *argv[])
{
int status;
int pid;
char *prog_arv[4];
/*
* Build argument list
*/
/* Remove the path or make the path correct for your system, as needed */
prog_argv[0] = "/usr/local/bin/ls";
prog_argv[1] = "-l";
prog_argv[2] = "/";
prog_argv[3] = NULL;
/*
* Create a process space for the ls
*/
if ((pid=fork()) < 0)
{
perror ("Fork failed");
exit(errno);
}
if (!pid)
{
/* This is the child, so execute the ls */
execlp (prog_argv[0], prog_argv[0], prog_argv[1], prog_argv[2], NULL);
exit(EXEC_FAILED);
}
if (pid)
{
/*
* We're in the parent; let's wait for the child to finish
*/
waitpid (NULL); /* Could also be waitpid(pid, NULL, 0); */
}
}
Important Things To Remember