2016-05-12 127 views
0

我想把一个bash脚本(sc.sh),这是在这个程序,并包含下面的行,在同一目录输出到C程序(cprog) ;执行cprog作品,但我不知道为什么在bash脚本没有启动:叉执行和管道与bash脚本

timeout 5 cat /dev/urandom 

,这是主要的程序:

#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

int main(int argc, char* argv[]) 
{ 
    int fd[2]; 
    pid_t pid1, pid2; 
    char * input[] = {"/bin/bash", "sc.sh", argv[1], NULL}; 
    char * output[] = {"./cprog", argv[1], NULL}; 

    pipe(fd); 

    pid1 = fork(); 
    if (pid1 == 0) { 
     dup2(fd[1], STDOUT_FILENO); 
     close(fd[0]); 
     execv(input[0], input); 
     return 1; 
    } 

    pid2 = fork(); 
    if (pid2 == 0) { 
     dup2(fd[0], STDIN_FILENO); 
     close(fd[1]); 
     execv(output[0], output); 
     return 1; 
    } 

    close(fd[0]); 
    close(fd[1]); 
    waitpid(pid1, NULL, WNOHANG); 
    waitpid(pid2, NULL, WNOHANG); 
    return 0; 
} 
+2

Szymon,你应该考虑使用缩进。 :) – ZbyszekKr

+1

你应该检查函数调用的返回值。 –

+1

你需要'bash -c'。 – EOF

回答

1

我修改程序报告错误,实际上等待孩子死,像这样:

#include <stdio.h> 
#include <sys/wait.h> 
#include <unistd.h> 

int main(int argc, char* argv[]) 
{ 
    if (argc > 2) 
     fprintf(stderr, "Excess arguments ignored\n"); 
    int fd[2]; 
    pid_t pid1, pid2; 
    char * input[] = {"/bin/bash", "sc.sh", argv[1], NULL}; 
    char * output[] = {"./cprog", argv[1], NULL}; 

    pipe(fd); 

    pid1 = fork(); 
    if (pid1 == 0) { 
     dup2(fd[1], STDOUT_FILENO); 
     close(fd[0]); 
     close(fd[1]); 
     execv(input[0], input); 
     perror(input[0]); 
     return 1; 
    } 

    pid2 = fork(); 
    if (pid2 == 0) { 
     dup2(fd[0], STDIN_FILENO); 
     close(fd[0]); 
     close(fd[1]); 
     execv(output[0], output); 
     perror(output[0]); 
     return 1; 
    } 

    close(fd[0]); 
    close(fd[1]); 
    int status1; 
    int corpse1 = waitpid(pid1, &status1, 0); 
    printf("PID %d: %d (0x%.4X)\n", pid1, corpse1, status1); 
    int status2; 
    int corpse2 = waitpid(pid2, &status2, 0); 
    printf("PID %d: %d (0x%.4X)\n", pid2, corpse2, status2); 
    return 0; 
} 

我用一个简单的C程序作为cprog

#include <stdio.h> 

int main(void) 
{ 
    int c; 
    unsigned sum = 0; 
    unsigned cnt = 0; 
    while ((c = getchar()) != EOF) 
     sum += c, cnt++; 
    printf("sum of bytes: %u\n", sum); 
    printf("num of bytes: %u\n", cnt); 
    return 0; 
} 

测试在命令行上产生:

$ bash sc.sh | cprog 
sum of bytes: 325895667 
num of bytes: 69926912 
$ 

运行主程序(它是从p19.c创建p19)产生:

$ ./p19 
sum of bytes: 372818733 
num of bytes: 70303744 
PID 28575: 28575 (0x7C00) 
PID 28576: 28576 (0x0000) 
$ 

退出状态表明timeout退出,状态124,这是GNU文档在命令超时时退出的状态。

因此,在您的环境中,您提供的代码工作正常。这表明您的环境没有按照您的想法设置。也许sc.sh脚本不在那里。

+0

谢谢,我设法通过关闭这些文件描述符并重写cprog来解决这个问题。你的代码真的很有用。 – Szymon