c - 系统 ("echo text > t.log") 报告错误

标签 c linux shell

下面的代码是为了获取和设置RLIMIT_NOFILE,然后执行execsystem:

#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/

相关文章:

c - 分配字符串时指针存储什么地址?

shell - Jenkins - java.io.IOException : Cannot run program "/usr/local/bin/bash"

c - 编译包含<math.h>的c代码时需要使用额外的选项

c - 管道在 Linux 中是如何工作的?

C - 用户输入被跳过?

c - 如何使用makefile链接依赖库

linux - 尝试更改我的 Ubuntu 桌面的屏幕分辨率

linux - 如何在英特尔显卡上为 "monitor plugged"创建回调?

mysql - 支持 MySQL 的 linux 的低开销语言是什么?

shell - applescript 'Can’ t 将当前应用程序转换为字符串类型'