C 程序在 Popen 不起作用后挂在 Fgets 上



EDIT:我编写了一个生成可逆函数的 C 程序,并将它们写入执行并打开的 R 文件中popen.我在 Ubuntu 16.04 上运行这个程序。我的程序编译,但 R 脚本从未完成/挂起

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define num_func 10
char * makeInvert(){
char * buffer = malloc(200 * sizeof(char));
double a = (double)(rand()%5)-5.0; 
double b = (double)(rand()%5)-5.0; 
double c = (double)(rand()%5)-5.0; 
double n = (double)(rand()%5)-5.0;
n *= 2;
n += 1;
sprintf(buffer, "%g(x + %g)^%g + %g == y", a, b, n, c);
return buffer;
}
int main() {
printf("entered main n");
int i;
char * buff1;
for (i = 0; i < num_func; i++) {
char R[5000];
buff1 = makeInvert();
strcpy(R, "library(Ryacas)n");
strcat(R, "yacas("Solve(");
strcat(R, buff1);
strcat(R, ", x)")nn");
//sleep(1);
char filename[100];
strcpy(filename, "computation/");
strcat(filename, "inverse");
strcat(filename, ".R");
FILE * f = fopen(filename, "w");    
if (!f) {       //validate file is open 
printf("cant open file");
}
fputs(R, f);
printf("before fclose");
fflush(stdout);
fclose(f);
f = NULL;
printf("after fclose");
fflush(stdout);
char path[5000];
char command[300];
strcpy(command,"Rscript ");
strcat(command, "computation/inverse");
strcat(command, ".R");
printf("command %sn", command);
FILE * fp = popen(command, "r");
if (!fp) {       //validate file is open 
printf("cant open file");
fflush(stdout);
}
printf("after popenn");
fflush(stdout);
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("output: %sn", path);
}
fclose(fp);
}
return 0;
}

运行strace -f program_name的输出

execve("/usr/bin/test", ["test"], [/* 20 vars */]) = 0
brk(NULL)                               = 0x16ef000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f95f15a9000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=53425, ...}) = 0
mmap(NULL, 53425, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f95f159b000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "177ELF21133>1Pt2"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1868984, ...}) = 0
mmap(NULL, 3971488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f95f0fbc000
mprotect(0x7f95f117c000, 2097152, PROT_NONE) = 0
mmap(0x7f95f137c000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1c0000) = 0x7f95f137c000
mmap(0x7f95f1382000, 14752, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f95f1382000
close(3)                                = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f95f159a000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f95f1599000
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f95f1598000
arch_prctl(ARCH_SET_FS, 0x7f95f1599700) = 0
mprotect(0x7f95f137c000, 16384, PROT_READ) = 0
mprotect(0x60a000, 4096, PROT_READ)     = 0
mprotect(0x7f95f15ab000, 4096, PROT_READ) = 0
munmap(0x7f95f159b000, 53425)           = 0
brk(NULL)                               = 0x16ef000
brk(0x1710000)                          = 0x1710000
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=1668976, ...}) = 0
mmap(NULL, 1668976, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f95f1400000
close(3)                                = 0
close(1)                                = 0
close(2)                                = 0
exit_group(1)                           = ?
+++ exited with 1 +++

当我直接运行Rscript computation/inverse.R时,它会挂起并且不输出任何内容。


我相信它挂在fgets上,因为当我在 gdb 上运行程序进行回溯时,我看到这个:

after popen 
^C
Program received signal SIGINT, Interrupt.
0x00007ffff7b04230 in __read_nocancel ()
at ../sysdeps/unix/syscall-template.S:84
84  ../sysdeps/unix/syscall-template.S: No such file or directory.
(gdb) backtrace
#0  0x00007ffff7b04230 in __read_nocancel ()
at ../sysdeps/unix/syscall-template.S:84
#1  0x00007ffff7a875e8 in _IO_new_file_underflow (fp=0x6034f0) at fileops.c:592
#2  0x00007ffff7a8860e in __GI__IO_default_uflow (fp=0x6034f0) at genops.c:413
#3  0x00007ffff7a7bc6a in __GI__IO_getline_info (fp=fp@entry=0x6034f0, 
buf=buf@entry=0x7fffffffd1d0 "", n=4998, delim=delim@entry=10, 
extract_delim=extract_delim@entry=1, eof=eof@entry=0x0) at iogetline.c:60
#4  0x00007ffff7a7bd78 in __GI__IO_getline (fp=fp@entry=0x6034f0, 
buf=buf@entry=0x7fffffffd1d0 "", n=<optimized out>, delim=delim@entry=10, 
extract_delim=extract_delim@entry=1) at iogetline.c:34
#5  0x00007ffff7a7ab7d in _IO_fgets (buf=0x7fffffffd1d0 "", n=<optimized out>, 
fp=0x6034f0) at iofgets.c:53
#6  0x0000000000401288 in main () at test.c:123
(gdb) frame 6
#6  0x0000000000401288 in main () at test.c:123
123     while (fgets(path, sizeof(path)-1, fp) != NULL) {

看完这篇文章,我popen后添加了这段代码

int fd = fileno(fp);
int flags;
flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);

这篇文章解释说,"在Linux(或任何Unix-y操作系统(中,你可以将popen((使用的底层文件描述符标记为非阻塞。[使用上面的代码]如果没有可用的输入,fgets 将返回 NULL,并将 errno 设置为 EWILLBLOCK。当我现在运行 gdb 时,我得到:

after popen 
^C
Program received signal SIGINT, Interrupt.
0x00007ffff785f188 in _IO_new_proc_close (fp=0x6034f0) at iopopen.c:339
339 iopopen.c: No such file or directory.
(gdb) bt
#0  0x00007ffff785f188 in _IO_new_proc_close (fp=0x6034f0) at iopopen.c:339
#1  0x00007ffff7869960 in _IO_new_file_close_it (fp=fp@entry=0x6034f0) at fileops.c:172
#2  0x00007ffff785d3ef in _IO_new_fclose (fp=0x6034f0) at iofclose.c:58
#3  0x00000000004013f9 in main () at test.c:130
(gdb) frame 3
#3  0x00000000004013f9 in main () at test.c:130
130     fclose(fp);
(gdb) 

我没有浏览整个代码,但我发现了这个缺陷:

char R[5000];
buff1 = makeInvert();
strcat(R, "library(Ryacas)n");
strcat(R, "yacas("Solve(");

strcat"图书馆..."到未初始化的字符串上。您应该像在其他地方一样对第一个字符串使用strcpy或插入R[0]='';.

如果使用非阻塞 I/O,fgets(( 将在没有输出可用时立即退出。 这似乎不是你想要的。 您想读取整个输出然后退出。 我建议删除 fcntl(( 部分。

问题似乎是您的 R 脚本未完成。 我建议通过 strace -f 运行您的程序并发布输出。 另外,您是否尝试过运行"Rscript计算/逆。R",并确保它确实返回您期望的输出并且正在退出(如果没有,fgets 会被卡住(? 当您的进程被阻塞时,您是否看到 Rscript 是否仍在运行(我希望它确实如此,这就是您的进程卡住的原因(

你仍然有一些不相关的问题:你用fclose((而不是pclose((关闭popen(( fd。 如果 fopen(文件名,"w"(失败,您不会退出,因此它会崩溃。

自从发布评论和先前的答案以来,当前发布的代码似乎已被编辑。

为避免混淆,添加编辑,不要覆盖原始问题。

调用任何堆分配函数(malloc、calloc、realloc(时

  • 表达式:sizeof(char)定义为 1,将任何内容乘以 1 都没有效果。 建议删除该表达式。
  • 始终检查 (!=NULL( 返回值以确保操作成功
  • 当某些操作失败时,任何错误消息都应输出到stderr,而不是stdout因此请使用perror(),这也将输出操作系统认为操作失败的原因。

在宣布不可恢复的错误事件后,程序应该退出,而不是继续,就好像一切都"好"一样。

包含未使用的头文件是一种糟糕的编程实践。 建议删除包含语句:math.hfctrl.h

当使用popen()时,生成的文件描述符指针应该通过pclose()关闭,而不是fclose()

我采用了最新发布的代码并进行了几次简化和更正,结果如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define num_func 10

char * makeInvert( void );

char * makeInvert()
{
char * buffer = malloc(200);
if( !buffer )
{
perror( "malloc failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
double a = (double)(rand()%5)-5.0;
double b = (double)(rand()%5)-5.0;
double c = (double)(rand()%5)-5.0;
double n = (double)(rand()%5)-5.0;
n *= 2;
n += 1;
sprintf(buffer, "%g(x + %g)^%g + %g == y", a, b, n, c);
return buffer;
} // end function: makeInvert

int main( void )
{
printf("entered main n");
int i;
//char * buff1;
for (i = 0; i < num_func; i++)
{
FILE * f = fopen( "inverse.R", "w");
if (!f)
{       //validate file is open
//printf("cant open file");
perror( "fopen for computation/inverse.R for write failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
char R[5000];
strcpy(R, "library(Ryacas)nyacas("Solve(");
strcat(R, makeInvert());
strcat(R, ", x)")nn");
fputs(R, f);
//printf("before fclosen");
//fflush(stdout);
fclose(f);
f = NULL;
//printf("after fclosen");
//fflush(stdout);
//char command[300];
//strcpy(command, "Rscript computation/inverse.R");
//printf("command %sn", command);
FILE * fp = popen( "Rscript inverse.R", "r");
if (!fp)
{       //validate file is open
//printf("cant open file");
//fflush(stdout);
perror( "popen for inverse.R for read failed" );
exit( EXIT_FAILURE );
}
// implied else, popen successful
//printf("after popenn");
//fflush(stdout);
char path[5000];
while (fgets(path, sizeof(path)-1, fp) != NULL)
{
printf("output: %sn", path);
}
//fclose(fp);
pclose( fp );
}
return 0;
}

除此之外,请注意一致的缩进,以提高可读性。 编译器不在乎,但我们人类在乎。

注意:我的 Linux 16.04 上未安装R

结果 .R 文件包含:

library(Ryacas)
yacas("Solve(-2(x + -4)^-5 + -4 == y, x)")

运行修改后的代码的输出为:

entered main 
sh: 1: Rscript: not found
sh: 1: Rscript: not found
sh: 1: Rscript: not found
sh: 1: Rscript: not found
sh: 1: Rscript: not found
sh: 1: Rscript: not found
sh: 1: Rscript: not found
sh: 1: Rscript: not found
sh: 1: Rscript: not found
sh: 1: Rscript: not found

最新更新