spawn for Unix

Strange enough, but implementation of spawn() 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;
}
Comments:

Solaris already has posix_spawn(3C), at least in S10 and later...

Posted by Hugh on June 07, 2007 at 04:23 PM MSD #

I believe spawn is usually defined to start a process and not wait for it. Unix has had for a long time an interface for starting a command and waiting for it to complete: system().

Posted by Dave on June 07, 2007 at 05:03 PM MSD #

system() is something you should not be using these days

Posted by nacho on June 07, 2007 at 06:06 PM MSD #

system() start process using shell, I was doing this code to (re)implement JDK's Runtime.exec(), which can start arbitrary process. But I agree that spawn may be a bad name.

Posted by nike on June 08, 2007 at 04:04 AM MSD #

Post a Comment:
  • HTML Syntax: NOT allowed
About

nike

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
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
   
       
Today