C语言 Linux system()返回-1,ERRNO = 10无子进程[已关闭]

vsikbqxv  于 11个月前  发布在  Linux
关注(0)|答案(1)|浏览(225)

**已关闭。**此问题需要debugging details。目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
4年前关闭。
Improve this question
在RHEL 7.4中运行以下C代码:

errno = 0;

status = system("ls >> /tmp/test.txt");
sprintf(msg, "Value of errno: %d\n", errno);
sprintf(msg, "Status: %d ", status);
os_log_msg(msg);

字符串
我得到的返回码为-1和errno = 10(没有子进程)。/tmp/test. txt文件实际上是创建的,所以它可以工作,但是程序看到一个非零的返回码并退出。
问题是,这个命令在HP-UX 11.11中返回0,但我们迁移到RHEL 7.4,现在我们得到-1。

xcitsw88

xcitsw881#

如果初始创建子进程,system只能返回值-1(通过fork)或收集其退出状态(通过wait)失败。这两种情况都不会发生,因为传递给system的命令有问题,因为该命令是在子进程中解释的。该命令的问题将显示为system返回值s不等于0或-1,并且WIFEXITED(s) && WEXITSTATUS(s) != 0WIFSIGNALED(s)为真。(宏WIFEXITEDWIFSIGNALEDWEXITSTATUSsys/wait.h中定义。)(请参阅the POSIX specification for system以了解为什么会发生这种情况。)
fork故障通常只会在系统范围的资源耗尽和/或严重的强制资源配额时才会发生。

true: status=-1 errno=11 (Resource temporarily unavailable)

字符串
当我运行它。

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>

int main(void)
{
  struct rlimit rl;
  rl.rlim_cur = 1;
  rl.rlim_max = 1;
  setrlimit(RLIMIT_NPROC, &rl);

  int status = system("true");
  printf("true: status=%d errno=%d (%s)\n", status, errno, strerror(errno));
  return 0;
}


如果您有一个窃取等待状态的SIGCHLD处理程序,则system内部可能会发生wait故障。

true: status=-1 errno=10 (No child processes)


(SIGCHLD处理程序还有其他几种方式可以干扰system;这只是我能想到的最短的演示程序。)

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

int main(void)
{
  signal(SIGCHLD, SIG_IGN);

  int status = system("true");
  printf("true: status=%d errno=%d (%s)\n", status, errno, strerror(errno));
  return 0;
}


你说你传递给system的任何命令都能正确执行,但是system仍然返回-1,这让我认为你的问题是由于waitSIGCHLD处理程序之间的交互不好。errno中的(ECHILD)与此假设一致,因为wait被记录为产生该错误代码,而fork不是。
我必须强调,这是一个假设的基础上提供的信息。为了确保这是正确的,我们需要看到一个 * 完整的 * 测试程序,我们可以编译和运行自己,并观察到完全相同的失败条件,你是。请阅读并按照说明在https://stackoverflow.com/help/mcve

相关问题