How to set timeout for gcc compilation of .c file on linux - c

I am trying to compile a C code through my php script using gcc on a linux machine. But if the C code contains an infinite loop , the compiler gets stucked.
my PHP script goes like this ..
shell_exec('gcc input.c -o output 2> compile.txt');
$output=shell_exec('./output');
The 'input.c' file goes like this..
#include<stdio.h.
void main()
{
while(1)
prinf("This is infinite loop");
}
When I compile the PHP code , it gives an
**PHP Fatal error: Out of memory (allocated 403177472) (tried to allocate 804896768 bytes)**
I've tried timeout 5s :
$output=shell_exec('./output');
but it doesn't work although it works if i do ..
int i;
while(1)
{
scanf("%d",&i);
}
..in my input.c file. I have seached a lot but in vain..
What am I doing wrong.?

The first point is that, it is not the compiler which is getting stuck. The compiler compiles code fine. It is during execution that your code is going into a infinite loop. So, incase of your first code, it just keeps executing without any pause or exit and hogs the CPU all the time which gives a feeling of "being stuck".
With regard to how your second code works, it is because you are pausing for getting an input. But, again, in that case, you have failed provide an exit for your program. So, effectively, the second code is same as your first code, but it just doesn't hog the CPU.
There is only one way for you to correct this problem, that is by modifying your 'C' code not to have an infinite loop without any exit.
Example:
int i;
while(1)
{
scanf("%d",&i);
if(0 == i)
{
break; //Just an example as to how you can exit from an infinite loop
}
}

You can use ulimit in the invocation of the program. E.g. the following will limit output to 1 second of CPU time:
shell_exec("ulimit -t 1; ./output")
It might be a good idea to limit other resources too, so that output can't use all your memory etc.
(Note that this limits CPU time, not absolute time. If you want to do that, you should look at a program like timelimit, which would be called like shell_exec("timelimit -T 1 ./output"), I think.)

Jay explains much of it very well. The rest of it is that your first program not only goes into an infinite loop, but also produces an infinite amount of output, all of which you try to store in $output. I'd say you're lucky you didn't crash your computer, but PHP probably saved you with a built-in memory limit.

What you are looking for is possible theoretically:
You can read about the halting problem
However, you can probably use something like PHP's set_time_limit

Related

Why is this C program doing nothing in Ubuntu?

My very simple C program just hangs and I don’t know why.
I am trying to make a simple executable to handle multiple monotonous actions for me every time I start a new programming session.
So I decided with something simple (below) yet every time I run it, the app just hangs, never returns. So I have to Ctrl-C out of it. I have added printf commands to see if it goes anywhere, but those never appear.
My build command returns no error messages:
gcc -o tail tail.c
Just curious what I am missing.
#include <stdio.h>
#include <unistd.h>
int main() {
chdir("\\var\\www");
return 0;
}
There are at least two problems with the source code:
It is unlikely that you have a sub-directory called \var\www in your current directory — Ubuntu uses / and not \ for path separators.
Even if there was a sub-directory with the right name, your program would change directory to it but that wouldn't affect the calling program.
You should check the return value from chdir() — at minimum:
if (chdir("/var/www") != 0)
{
perror("chdir");
exit(EXIT_FAILURE);
}
And, as Max pointed out, calling your program by the name of a well-known utility such as tail is likely to lead to confusion. Use a different name.
Incidentally, don't use test as a program name either. That, too, will lead to confusion as it is a shell built-in as well as an executable in either /bin or /usr/bin. There is also a program /bin/cd or /usr/bin/cd on your machine — it will check that it can change directory, but won't affect the current directory of your shell. You have to invoke it explicitly by the full pathname to get it to run at all because cd is another shell built-in.
Two things:
First, that's not what Linux paths look like
Second, check the return value from chdir()
ie
if (chdir("/var/www") != 0)
printf("failed to change directory");
Finally, the effect of chdir() lasts for the duration of the program. It will not change the current directory of your shell once this program finishes.
The other answers adequately cover the issues in your C code. However, the reason you are seeing it hang is because you chose the name tail for your program.
In Linux, tail is a command in /usr/bin in most setups, and if you just type tail at the command line, the shell searches the $PATH first, and runs this. Without any parameters, it waits for input on its stdin. You can end it by pressing control-d to mark the end of file.
You can bypass the $PATH lookup by typing ./tail instead.
$ tail
[system tail]
$ ./tail
[tail in your current directory]
It is a good idea to use ./ as a habit, but you can also avoid confusion by not naming your program the same as common commands. Another name to avoid is test which is a shell built-in for testing various aspects of files, but appears to do nothing as it reports results in its system return code.

Code wont compile or throw an error when using scanf in C, gets stuck building forever

I want to preface this with the information that I am pretty inexperience with coding.
Whenever I try to compile my code, it never finishes building and never throws an error. I then have to use Task Manager to stop stuck.exe (stuck is the name of the c file) so that I can try to compile again. I have narrowed down the issue to having something to do with the scanf function.
#include <stdio.h>
int main(void) {
int number = 0;
printf("this line shouldn't break anything. number = %d\n", number);
printf("what should the new value of number be?: ");
scanf("%d", &number);
return 0;
}
When I remove the line that has the scanf function, the rest of the code compiles as it should.
I am doing all of this in SublimeText3 on Windows 10 and using GCC provided by MinGW.
Any information you can give to help me would be appreciated, and If you would like any more information please let me know.
If you have a process stuck.exe, it means that the program finished compiling and was automatically started by the IDE/text editor. scanf reads from standard input, but apparently the IDE does not execute it in an interactive fashion, so that you cannot enter the number via the IDE.
In your IDE, you need to use the Compile or Build command (and not Run), and invoke stuck.exe manually in a command shell window.
Even my compiler is GCC-MinGW and i use Vscode, And your program works just fine even with online compilers.Maybe there is a problem with your C installation or check if your system memory near to full it might cause problems like these sometimes.

How to remove execution related text from output window of Code::Blocks

I am using Code::Blocks for programming in C. When I compile my program and execute it, the output window (i.e.. Windows Command prompt) displays some execution related text, these texts are not of use to me right now and dont want them to appear(see text below).
Hello, World!
Process returned 0 (0x0) execution time : 3.920 s
Press any key to continue.
I tried to change the settings in Code::Blocks but couldn't find any settings related to the output window and also I dont want the text "Press any key to continue" to appear. These texts appear only if I run the program through Code::Blocks and doesn't appear if I directly run the program.
Unfortunately, some things just cannot be changed, and that is one of them. There are some quirks used by some IDE's that just drive programmers crazy, but it can't be helped. There is a reason why it's there: the execution data can be used to find out whether the program worked properly (e.g. ended execution). You can use this data later when targeting execution time as one of the main focuses in coding the project. There may be other uses for it as you code more and more advanced projects.
It only appears when you execute your code from the compiler. It does not need getch() function to stop the screen.
But if you execute its .exe file directly, outside the compiler, you will notice that annoying message 'Process returned 0 (0x0) execution time : 3.920 s' doesn't show anymore. Moreover, you will need getch() function to stop the screen.
you may need to include stdio.h and then call getchar() before return 0
for example;
#include <iostream>
//add this library
#include <stdio.h>
using namespace std;
int main()
{
cout<<"I am a C++ programmer! "<<"Awesome!";
//add this line of code
getchar();
return 0;
}

Error when running the same program repeatedly in Turbo C using DosBox in Windows7 64bit

I am trying to use Turbo C with DosBox (DosBox 0.74) in my Windows 7 64 bit.
The program works perfectly fine its first run. It compiles successfully without error and also executes flawlessly.
As I try to repeat running the same program, the prorgams seems to generate weird output. Thus the same program which worked perfectly now creates error output though it still compiles successfully.
The following is a program which places a polygon vertices in space depending on the number of vertices. In it's first runs it generates perfectly expected output but as I repeat it it creates completely wrong output. The vertices are placed in completely random locations.
I doubt if it is something related to memory. When I tried using a different emulator also similar error repeated!
Update 1:
I just tried with Mac OSX and the same error is repeating.
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>
int main()
{
int gd=DETECT,gm,count,i,x[100],y[100],r=100;
initgraph(&gd,&gm,"c:\\tc\\");
printf("Enter the number of cordinates:");
scanf("%d",&count);
printf("Entered count :%d",count);
for(i=0;i<count;i++)
{
x[i]=r*cos(2*3.14*(i+1)/count)+200;
y[i]=r*sin(2*3.14*(i+1)/count)+200;
circle(x[i],y[i],5);
}
getch();
return 0;
}
change one configuration in the file dosbox-0.74.conf
from
core=auto
to
core=normal
reopen dosbox again and test your program, it can run accurately for sure! Done!

How can I see an the output of my C programs using Dev-C++?

I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista.
So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output.
How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution, System("pause"), and a really ugly C solution, while looping fflush(stdout), but nothing nice and pretty.
I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
Use #include conio.h
Then add getch(); before return 0;
The easiest thing to do is to run your program directly instead of through the IDE. Open a command prompt (Start->Run->Cmd.exe->Enter), cd to the folder where your project is, and run the program from there. That way, when the program exits, the prompt window sticks around and you can read all of the output.
Alternatively, you can also re-direct standard output to a file, but that's probably not what you are going for here.
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Add this to your header file #include
and then in the end add this line : getch();
You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.
Add a line getchar(); or system("pause"); before your return 0; in main function.
It will work for you.
;
It works...
#include <iostream>
using namespace std;
int main ()
{
int x,y; // (Or whatever variable you want you can)
your required process syntax type here then;
cout << result
(or your required output result statement); use without space in getchar and other syntax.
getchar();
}
Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program.
It will show you the output window and it will not vanish with a second Until you click enter to close the output window.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.
The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.

Resources