Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: programatic tool interaction



On Thu, Dec 22, 2005 at 09:37:02AM +1300, Paul M wrote:
> You need to fork off a new process then exec the tool from the child. 
> The child process does not return. You can open pipes prior to the 
> fork, since the parent and child process share file descriptors.
> 
> Something like this:
> 
>     int socks[2];
> 
>     /* open socket pair */
>     int retval = pipe(socks);
>     if (retval < 0)
>       perror("opening socket pair");
> 
>     /* fork off a child process */
>     pid_t pid = fork();
>     if (pid == -1)
>       perror("Failed to fork\n");
> 
>     if (pid == 0) {
>       /* child process */
>       close(socks[1]);
>       dup2(socks[1], 2);

       dup2(socks[1], 1);
       close(socks[1]);

But he wants two way communication, so he will have to create to pipes
or use socketpair:

void childreap(int s) {
  while (waitpid(0, NULL, WNOHANG) > 0);
}

creatproc() {
int p[4];
pipe(p);
pipe(p+2);

switch (fork()) {
  case -1:
    /* error */
    ...
  case 0:
    /* child */
    dup2(p[0], STDIN_FILENO);
    dup2(p[3], STDOUT_FILENO);
    close(p[0]);
    close(p[1]);
    close(p[2]);
    close(p[3]);
    execl(program, program, arg1, arg2, ..., NULL);
    perror(program);
    exit(1);
  default:
    close(p[0]);
    close(p[3]);
    into_proc = p[1];
    from_proc = p[2];
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, childreap);
}

with socketpair:

creatproc() {
int p[2];
socketpair(PF_UNIX, SOCK_STREAM, p);

switch (fork()) {
  case -1:
    /* error */
    ...
  case 0:
    /* child */
    dup2(p[0], STDIN_FILENO);
    dup2(p[0], STDOUT_FILENO);
    close(p[0]);
    close(p[1]);
    execl(program, program, arg1, arg2, ..., NULL);
    perror(program);
    exit(1);
  default:
    close(p[0]);
    from_into_proc = p[1];
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, childreap);
}


Care must be given to prevent deadlocks (trying to write to the process
while it's trying to read from stdin and vice-versa).

Either use poll or select.

-- 
lfr
0/0
 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Unix-porting mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/unix-porting/email@hidden

This email sent to email@hidden

References: 
 >programatic tool interaction (From: Kevin Packard <email@hidden>)
 >Re: programatic tool interaction (From: Paul M <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.