File: forkexec.c

package info (click to toggle)
dmtcp 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,496 kB
  • sloc: cpp: 33,592; ansic: 28,099; sh: 6,735; makefile: 1,950; perl: 1,690; python: 1,241; asm: 138; java: 13
file content (95 lines) | stat: -rw-r--r-- 2,062 bytes parent folder | download
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>

static const int WELL_KNOWN_FD = 10;

static void die ( const char* msg )
{
  printf ( "ERROR: %s \n", msg );
  _exit ( -1 );
}

int main ( int argc, char** argv )
{
  FILE* fp = NULL;

  if ( argc == 1 ) // child will have argc == 2, argv[1] == "slave"
  {
    //coordinator

    int fd[2];
    if ( socketpair ( AF_UNIX,SOCK_STREAM,0,fd ) != 0 ) die ( "pipe() failed" );

//         char buf[] = "TEST";
//         write(fd[1], "test", sizeof buf);
//         read(fd[0], buf, sizeof buf);
//
//         printf("%s\n",buf);


    if ( fork() == 0 )  // if child
    {
      //oops... the user forgot to close an unused socket!!!
      //close(fd[1]);
      dup2 ( fd[0], WELL_KNOWN_FD );
      char* t[] = { argv[0] , "slave", 0};
      // BAD USER: just trashed our environment variables:
      char* env[] = {"A=B","C=E","LD_PRELOAD=taco",0,0};

      // On some systems, LD_LIBRARY_PATH might point to a required run-time
      // library
      if ( getenv("LD_LIBRARY_PATH") != (char*)NULL ) {
        static char ldpath[2048];
        sprintf ( ldpath, "LD_LIBRARY_PATH=%s", getenv("LD_LIBRARY_PATH") );
        env[3] = ldpath;
      }

      execve ( argv[0], t, env );
      perror ( "execve" );
      die ( "exec failed" );

    }
    else  // else parent
    {
      close ( fd[0] );
      dup2 ( fd[1],WELL_KNOWN_FD );

      char c;

      while ( read ( 0,&c,1 ) )
      {
//                 if(c=='\n') c = '\n';
//                 printf("sending: %c\n",c);
        while ( write ( WELL_KNOWN_FD, &c, 1 ) != 1)
          continue;
      }

      die ( "parent done" );

    }
  }

  //client
  {
//         char* lineptr = NULL;
//         size_t n = 0;
    fp = fdopen ( WELL_KNOWN_FD,"rw" );
    if ( fp == NULL ) die ( "fdopen failed" );

    char c;

    while ( read ( WELL_KNOWN_FD,&c,1 ) )
    {
      printf ( " %c",c ); fflush(stdout);
    }

    die ( "child done" );
  }

  return 0;
}