下面的代码是为了获取和设置RLIMIT_NOFILE
,然后执行exec
和system
:
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void show_nofile()
{
struct rlimit rl;
if (getrlimit(RLIMIT_NOFILE, &rl)) {
perror("getrlimit");
}
printf("rlim_cur = %ld, rlim_max =%ld\n", rl.rlim_cur, rl.rlim_max);
}
int set_nofile(long cur, long max)
{
struct rlimit rl;
rl.rlim_cur = cur;
rl.rlim_max = max;
if (setrlimit(RLIMIT_NOFILE, &rl)) {
perror("setrlimit");
return -1;
}
return 0;
}
int main(int argc, char* argv[])
{
show_nofile();
if (argc<2) {
set_nofile(9, 10);
show_nofile();
printf("now execlp...\n");
execlp("./a.out", "a.out", "-n", (char*)NULL);
} else {
if (-1==system("/bin/echo abc > log")) {
perror("system");
}
}
return 0;
}
我是这样编译运行的gcc -Wall limit.c && ./a.out
,结果是:
rlim_cur = 1024, rlim_max =4096
rlim_cur = 9, rlim_max =10
now execlp...
rlim_cur = 9, rlim_max =10
sh: 1: 1: Invalid argument
这里可能有什么问题?
附言:
我在我的主目录中运行它,所以没有权限问题。
此外,错误消息似乎与文件权限无关。
最佳答案
问题是您为 RLIMIT_NOFILE
设置的限制太低。
strace
你的程序,你会发现像这样的行
10512 open("def", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
10512 fcntl(1, F_DUPFD, 10) = -1 EINVAL (Invalid argument)
10512 close(1) = 0
这意味着 sh
无法成功重定向 I/O。
请替换
set_nofile(9, 10);
与
set_nofile(12, 20);
再试一次。
关于c - 系统 ("echo text > t.log") 报告错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22138954/