1

I have the bellow bit of code that works just fine.

  FILE *pipe_fp;
  if((pipe_fp = popen("php", "w")) == NULL) {
    perror("popen(PHP)");
    exit(1);
  }

  fputs("<?php echo process('xx'); ?>", pipe_fp);
  int ret = pclose(pipe_fp);
  if(WIFEXITED(ret))
    printf("%d\n", WEXITSTATUS(ret));

The problem is when I try something like this:

// up to this point i am starting a socket servers and wait for clients
int bSize;
int nSize;
char buffer[MAXBUF+1];
char receive[MAXBUF+1];
while(1) {
  bSize = recv(new_fd, buffer, MAXBUF, 0);
  if(bSize > 0) {
    buffer[bSize] = '\0';
    strcat(receive, buffer);
  }
}

// I rote this part based on this post: http://stackoverflow.com/questions/1383649/concatenating-strings-in-c-which-method-is-more-efficient
char * first= "<?php echo process('";
char * second = "'); ?>";
char * code = NULL;
asprintf(&code, "%s%s%s", first, receive, second);

// the above code somes here, i just copied the part that has changed
fputs(code, pipe_fp);

I have tried a bunch of other examples all resulting in failure. I am 3 days old at C.

transilvlad
  • 13,974
  • 13
  • 45
  • 80

3 Answers3

1

Instead of using a temporary file, you can start the php process and pass your script to stdin, getting the results from stdout.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
  • Yes that is also a similar approach. I am looking for something similar to apache that does not require me to go through the entire apache source code to find out how they did it. I bet others have tried to do this to and there must be some dummy guide to this. – transilvlad Oct 05 '12 at 10:41
0

You probably want to use the system() call where you can start up PHP and run your script.

Rob
  • 14,746
  • 28
  • 47
  • 65
0

I have a code which replaces stdin:

int spipe[2];
if( pipe(spipe) == -1 )
    return 0;
int pid = fork();
if( pid == -1 )
    return 0;
if( !pid )
{
    close(spipe[1]);
    dup2(spipe[0], 0); //dup2(spipe[0], stdin);
    if( execl(PROGRAM_NAME, PROGRAM_NAME, PROGRAM_PARAM, NULL) != 0 )
        exit(1);
}
close(spipe[0]);

You can replace stdout with another pipe the same manner.

Pavel Ognev
  • 962
  • 7
  • 15