c - 从 C 内部运行 csh

标签 c exec csh

我想从我的 C 程序运行一个 csh 命令。我使用以下代码完成了此操作:

char *csh_command[3];
...
csh_command[2]=(char*)malloc((length_command+strlen("\"\""))*sizeof(char));

csh_command[0]=(char*)malloc((strlen("-f")+1)*sizeof(char));
csh_command[1]=(char*)malloc((strlen("-c")+1)*sizeof(char));

strcat (csh_command[0],"-f");
strcat (csh_command[1],"-c");
strcat (csh_command[2],"\"");
strcat (csh_command[2],full_command);
strcat (csh_command[2],"\"");
pid=fork();
if (pid == 0){
        execvp("csh", csh_command);
}

我在这里所做的是创建一个包含 csh 参数的数组: -f, -c, "[要运行的命令]"

但是结果不是预期的那样。子进程只是在后台运行,什么都不做。

我们尝试运行 ls | wc -l 使用它。

问题出在哪里?

编辑:

length_command 变量已经为 \0 +1。问题在于数组未以 NULL 终止。而 " 是不必要的。

最佳答案

我看到的第一个错误

The array of pointers must be terminated by a NULL pointer.

尝试:

char *csh_command[4];
csh_command[3] = 0;

length_command 值是多少?它应该至少是 strlen(full_command)+1

更新:

另一个问题可能与 strcat 有关,因为您使用的是未初始化的字符串,它们可能包含一些垃圾。至少执行以下操作:

char *str = (char *)malloc(strlen("blabla")+1);
str[0] = '\0';
strcat(str, "blabla");

或者只使用 strdup 而不是 malloc+strcat

关于c - 从 C 内部运行 csh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5680848/

相关文章:

C:括号错误

java - 使用来自 Java 的重定向标准输入和标准输出运行外部程序

redis - phpredis中的MULTI/EXEC命令是否一次发送命令?

ant - 如何使用 Apache Ant exec 任务记录 cmd tree 命令的输出?

csh - 在 unix 中继续

清除 double 的尾随 0?

c++ - 错误消息 : Invalid operands of types 'float' and 'int' to binary 'operator%'

c - 二叉树中的负数

linux - UNIX\Linux : How to add a directory text to each line inside a file?

linux - 无法在 .cshrc 中获取脚本源