TheDude1142
TheDude1142

Reputation: 188

C: Issue with setting soft limit using RLIMIT_FSIZE

I was reading the Manual Pages about getrlimt/setrlimit and I was following the examples accordingly.

I am trying to set the "soft" limit, but when I set the soft limit and print it out, it comes out completely wrong.

Examples: I set the soft limit to 50, I get The soft limit is 219030298624. I set the soft limit to 100, I get The soft limit is 42953954893824. I set the soft limit to 100000 as listed in the code below and I get the same thing as above.

What is going on?

        struct rlimit limit;
        getrlimit (RLIMIT_FSIZE, &limit);
        limit.rlim_cur = 100000;
        setrlimit (RLIMIT_FSIZE, &limit);


        struct rlimit rl;
        getrlimit (RLIMIT_CPU, &rl);
        rl.rlim_cur = 1;     
        setrlimit (RLIMIT_CPU, &rl);

        printf("The soft limit is %llu\n", limit.rlim_cur);

Upvotes: 0

Views: 1530

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215387

%llu is not necessarily a valid format specifier for rlim_t. This is the source of the nonsensical huge values; you're invoking UB by passing mismatching types to printf. Cast to long long and the value printed should be correct.

Upvotes: 0

user590028
user590028

Reputation: 11728

setrlimit does not return the current value. You need to call getrlimit after setting the value to retrieve the current value.

 struct rlimit rl;
 getrlimit (RLIMIT_CPU, &rl);
 rl.rlim_cur = 1;     
 setrlimit (RLIMIT_CPU, &rl);

 getrlimit (RLIMIT_CPU, &rl);
 printf("The soft limit is %llu\n", rl.rlim_cur);

Or you can use prlimit to both set and get in one call http://linux.die.net/man/2/prlimit

Upvotes: 1

Related Questions