作为一个完整的程序,下面的代码在大多数情况下都能正常工作。
我可以让它挂起的唯一方法是如果test1.txt
是导致cp
挂起的特殊文件类型。例如mkfifo test1.txt
会给你有趣的结果。通过有趣的结果,我的意思是你必须用 CTRL+C、kill 等来终止程序。
您的问题很可能不在您发布的代码中。
/* copy.c,
compile using the command "gcc -o copy copy.c"
run using "./copy"
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CMD_SIZE 256
char cmd[CMD_SIZE];
int main(int argc, char **argv)
{
memset( cmd, 0, CMD_SIZE );
sprintf( cmd, "cp %s %s", "test1.txt", "test2.txt" );
system(cmd);
printf("cmd complete\n");
}
作为健全性检查,您可以尝试添加printf("%d\n", BUFSIZE)
以检查的值BUFSIZE
并printf("%s\n", cmd)
确保命令看起来确实像您想要的那样。