简体   繁体   中英

Calling gcc with shell_exec in php

<?php
$output=shell_exec('gcc prog.c');
echo "$output";
?>

I'm trying execute ac program using php and have used shell_exec to call gcc to execute the program but it is giving no output but there is no error being showed . Can please someone correct the mistake Thank you in advance.

gcc is used to compile the c file. It doesn't 'run' the .c file. Try it from your command line. You will notice after running gcc prog.c you have a file named 'a.out'. a.out is the executable that is created from the successful compile of prog.c

Calling gcc will launch a compile of the prog.c file. It's not executing it.

If you need your prog.c file to be compiled at runtime, I'd write a quick shell script that would look somewhat like that:

#!/bin/bash

rm prog_compiled_from_php               # Remove previously compiled program
GCC=`which gcc`                         # Find the path to gcc and store it in the "GCC" variable
$GCC prog.c -o prog_compiled_from_php   # Compile prog.c into the binary called prog_compiled_from_php
./prog_compiled_from_php                # Execute the compiled program

Save this file as prog_compile

Make sure you make this script executable, with this: chmod a+x prog_compile

From PHP, call $output = shell_exec('prog_compile');

I'm no bash script expert, feel free to correct my syntax :)

You can execute many cmd commands using && . To compile the C file and execute and echo the output, you can use this line of code :

$output = shell_exec('cd /path/to/c_file && gcc prog.c && a');
echo '&output';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM