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, "177ELF2113 3 >