Unix C 代码 cp in system()

发布于 2024-08-22 05:15:54 字数 239 浏览 10 评论 0原文

我有一个C代码.. 我有以下 UNIX 代码:

l_iRet = system( "/bin/cp -p g_acOutputLogName g_acOutPutFilePath");

当我运行生成的二进制文件时..我收到以下错误:

cp: cannot access g_acOutputLogName

任何人都可以帮助我吗?

I have a C code..
i which I have following code for UNIX:

l_iRet = system( "/bin/cp -p g_acOutputLogName g_acOutPutFilePath");

when I am running the binary generated..I am getting the following error:

cp: cannot access g_acOutputLogName

Can any one help me out?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

想你的星星会说话 2024-08-29 05:15:54

通常,您应该更喜欢 exec 函数系列而不是系统函数。系统函数将命令传递给 shell,这意味着您需要担心命令注入和意外的参数扩展。使用exec调用子进程的方法如下:

pid_t child;
child = fork();
if (child == -1) {
  perror("Could not fork");
  exit(EXIT_FAILURE);
} else if (child == 0) {
  execlp("/bin/cp", g_acOutputLogName, g_acOutPutFilePath, NULL);
  perror("Could not exec");
  exit(EXIT_FAILURE);
} else {
  int childstatus;
  if (waitpid(child, &childstatus, 0) == -1) {
    perror("Wait failed");
  }
  if (!(WIFEXITED(childstatus) && WEXITSTATUS(childstatus) == EXIT_SUCCESS)) {
    printf("Copy failed\n");
  } 
}

You should generally prefer the exec family of functions over the system function. The system function passes the command to the shell which means that you need to worry about command injection and accidental parameter expansion. The way to call a subprocess using exec is as follows:

pid_t child;
child = fork();
if (child == -1) {
  perror("Could not fork");
  exit(EXIT_FAILURE);
} else if (child == 0) {
  execlp("/bin/cp", g_acOutputLogName, g_acOutPutFilePath, NULL);
  perror("Could not exec");
  exit(EXIT_FAILURE);
} else {
  int childstatus;
  if (waitpid(child, &childstatus, 0) == -1) {
    perror("Wait failed");
  }
  if (!(WIFEXITED(childstatus) && WEXITSTATUS(childstatus) == EXIT_SUCCESS)) {
    printf("Copy failed\n");
  } 
}
丶情人眼里出诗心の 2024-08-29 05:15:54

据推测,g_acOutputLogNameg_acOutPutFilePath是程序中的char[](或char*)变量,而不是实际的变量涉及的路径。

您需要使用其中存储的值,而不是变量名称,例如:

char command[512];    
snprintf( command, sizeof command, "/bin/cp -p %s %s", 
          g_acOutputLogName, g_acOutPutFilePath );
l_iRet = system( command );

Presumably g_acOutputLogName and g_acOutPutFilePath are char[] (or char*) variables in your program, rather than the actual paths involved.

You need to use the values stored therein, rather than the variable names, for example:

char command[512];    
snprintf( command, sizeof command, "/bin/cp -p %s %s", 
          g_acOutputLogName, g_acOutPutFilePath );
l_iRet = system( command );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文