Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c program that runs itself using system

Tags:

I was learning about the function system() is stdlib.h and realized I could create a program that ran itself using system(). I wrote this code and tried it:

#include <stdio.h> #include <stdlib.h>  int main(){     printf("x");     system("./a.out"); } 

It print exactly 563 x's to console every time I run it before exiting normally (no errors). I would like to know what is stopping the program and where this number comes from as it seems very arbitrary to me. Thanks

Thanks for the insight regarding this first program but I'm not convinced the system is stopping it because it is running out of resources for the following reason: I just wrote this new program and it has not yet stopped.

#include <stdio.h> #include <stdlib.h>  int main(){     printf("x");     system("./a.out");     system("./a.out"); } 

Also, when I tried to open a new console window I got this error:

/.oh-my-zsh/lib/theme-and-appearance.zsh:24: fork failed: resource temporarily unavailable  /.oh-my-zsh/oh-my-zsh.sh:57: fork failed: resource temporarily unavailable 
like image 670
Mathew Avatar asked Dec 04 '16 02:12

Mathew


Video Answer


2 Answers

I'll tackle the second program first, since that's easiest to explain. Try this code instead which will print out the recursion depth as it goes.

#include <stdio.h> #include <stdlib.h> #include <string.h>  int main(int argc, char** argv){   int depth = argc > 1 ? atoi(argv[1]) : 0;   printf("%d\n", depth);   char cmd[128];   sprintf(cmd, "%s %d", "./a.out", depth+1);   system(cmd);   system(cmd); } 

It will grow up until your limit (in my case 538), then start trashing up and down the recursion tree.

530 531 532 533 534 535 536 537 538 538 537 538 538 536 537 

Eventually this process would finish, but it will take a very long time!

As for the first program. I believe you are just running into your user process limit.

You can find your process limit by running

ulimit -u 

In my case the limit is 709. Count my other processes running with

ps aux | grep user | wc -l 

That gives me 171. 171 + 538 (my depth at which the program died) gives a solid answer for you :)

https://superuser.com/questions/559709/how-to-change-the-maximum-number-of-fork-process-by-user-in-linux

like image 177
idle Avatar answered Sep 21 '22 14:09

idle


There is nothing in your program to stop the infinite recursion.

You execute a.out.     a.out executes a.out       a.out executes a.out         a.out executes a.out           a.out executes a.out   

and so on.

At some point, the system runs of of resources and does not execute the next system call and the programs exit in the reverse order. It appears that your computer reached the limit by the time it ran the program 563 times.

like image 43
R Sahu Avatar answered Sep 25 '22 14:09

R Sahu