0
char cmd[256];
memset(cmd,0,256);
sprintf(cmd, "cp %s %s", "test1.txt", "test2.txt");
system(cmd);
printf("cmd completed\n");

当我运行上述代码时,我的应用程序在系统调用时挂起。我从来没有到达 printf 行。我在带有 GCC 编译器的 Linux Centos 上运行。

任何帮助表示赞赏。

如果我在单独的应用程序中运行上述代码(在主应用程序中复制粘贴)。它运行良好。

4

1 回答 1

7

作为一个完整的程序,下面的代码在大多数情况下都能正常工作。

我可以让它挂起的唯一方法是如果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)以检查的值BUFSIZEprintf("%s\n", cmd)确保命令看起来确实像您想要的那样。

于 2012-04-12T19:58:14.147 回答