1

我有以下代码可以正常工作。

  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));

问题是当我尝试这样的事情时:

// 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);

我尝试了许多其他示例,都导致失败。我在 C 3 天大。

4

3 回答 3

1

您可以不使用临时文件,而是启动 php 进程并将脚本传递给 stdin,从 stdout 获取结果。

于 2012-10-05T10:36:01.077 回答
0

您可能希望使用system()可以启动 PHP 并运行脚本的调用。

于 2012-10-05T10:44:49.213 回答
0

我有一个替换标准输入的代码:

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]);

您可以以相同的方式将 stdout 替换为另一个管道。

于 2012-10-05T15:00:19.060 回答