日期:2014-05-16  浏览次数:20560 次

linux c 调用gcc命令
我想做一个c++或者c程序可以将一段源代码编译执行 可是在调用gcc时 如果源代码有错误程序捕获不到错误信息
用到了匿名管道
C/C++ code

 #include <stdio.h>
   #include <string.h>
   #include <sys/wait.h>
   #include <stdlib.h>
   #include <unistd.h>
     int mysystem(char* cmdstring, char* buf, int len)
     {
       int   fd[2];
       pid_t pid;
     int   n, count;
     memset(buf, 0, len);
    if (pipe(fd) < 0)
       return -1;
     if ((pid = fork()) < 0)
         return -1;
     else if (pid > 0)
     {
       close(fd[1]);
      count = 0;
      while ((n = read(fd[0], buf + count, len)) > 0 && count > len)
           count += n;
     close(fd[0]);
       if (waitpid(pid, NULL, 0) > 0)
              return -1;
     }
    else
      {
      close(fd[0]);
       if (fd[1] != STDOUT_FILENO)
      {
               if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
              {
                       return -1;
              }
               close(fd[1]);
 }
       if (execl("/bin/sh", "sh", "-c", cmdstring, (char*)0) == -1)
              return -1;
    }
     return 0;
   }
 
int main()
 {
  char buf[10];
   mysystem("gcc -o add add.c",buf,11);
 printf("=%s=",buf);
  return 0;
 }




和popen

C/C++ code

int main(void)
{
 FILE *stream;
  char buf[1024];
   memset(buf,'\0',sizeof(buf));
 stream = popen("gcc -o mail mail.c","r");
   fread(buf,sizeof(char),sizeof(buf),stream);
   fclose(stream);
 printf("qqqqq:%s:sss\n",buf);
  return 0;
 }




这是什么原因呢? 不有其他方法吗?

------解决方案--------------------
孩子, 一般错误都是打印到stderr的,gcc同样如此, 请将子进程的dup2(pipe[1], STDERR_FILENO);
------解决方案--------------------
简单点的话,你执行gcc的时候2>&1