adamsmith
adamsmith

Reputation: 6009

system("echo text > t.log") reports error

The following code is intend to get and set RLIMIT_NOFILE, then do exec and 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;
}

This is how i compile and run it gcc -Wall limit.c && ./a.out, the result is:

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

What could be wrong here?

P.S.: I run it in my home dir, so there is not permission problems.
Besides, the error message does not seem to relate file permission.

Upvotes: 1

Views: 71

Answers (3)

Lee Duhem
Lee Duhem

Reputation: 15121

The problem is that you set a too low limit for RLIMIT_NOFILE.

strace your program, you will find lines like

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

which means sh cannot redirect I/O successfully.

Please replace

set_nofile(9, 10);

with

set_nofile(12, 20);

and try again.

Upvotes: 1

Ganesh Sastry
Ganesh Sastry

Reputation: 1

There seems to be nothing wrong with the code as such.. Try to check the write permissions on the directory you are trying to execute the program in. On successful execution, your file "t.log" will only contain the word "text".

@Yunxuan Tuanmu: '$text' will be the shell's context, which will be null since it is not set within that context

Upvotes: 0

Yunxuan Tuanmu
Yunxuan Tuanmu

Reputation: 1

Is the "text" a variable? If so, you may need to try this:

system("echo $text > t.log");

Upvotes: 0

Related Questions