Nikolay Igotti
spawn for Unix
Strange enough, but implementation ofspawn() functionality, i.e. execute another program, wait for it's completion and return errno could be tricky for Unix (trickiest part is
errno handling). Following is a program I wrote some time ago to do that.
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int spawn(int argc, char** argv) {
int pipes[2];
int status = 0;
int pid;
if (pipe(pipes) != 0) {
perror("pipe");
return -1;
}
fcntl(pipes[1], F_SETFD, FD_CLOEXEC);
if ((pid = fork()) == 0) {
int err;
close(pipes[0]);
execv(argv[0], argv);
err = errno; // errno may be function in MT case
write(pipes[1], &err, sizeof(int));
exit(127);
}
close(pipes[1]);
if (read(pipes[0], &status, sizeof(int)) == 0) {
status = 0;
}
if (pid != -1) {
waitpid(pid, NULL, 0);
}
return status;
}
int main(int argc, char** argv) {
int s;
char* argv1[] = { "/bin/ls", NULL } ;
char* argv2[] = { "/bin/lsa", NULL} ;
s = spawn(1, argv1);
printf("for OK: %d, %s\n", s, strerror(s));
s = spawn(1, argv2 );
printf("for BAD: %d, %s\n", s, strerror(s));
return 0;
}
Posted at 09:49PM Jun 07, 2007 by nike in Sun | Comments[4]
Thursday Jun 07, 2007
Posted by Hugh on June 07, 2007 at 11:23 PM MSD #
Posted by Dave on June 08, 2007 at 12:03 AM MSD #
Posted by nacho on June 08, 2007 at 01:06 AM MSD #
Posted by nike on June 08, 2007 at 11:04 AM MSD #