0

I'm trying to write a C program to open separate terminal and ping google.com

#include<stdio.h>
#include <string.h>

int main()
{
char command[50];
strcpy(command,"gnome-terminal -e 'sh -c "ping -c4 google.com"'");
system(command);

return (0);
}

But it only shows error message like this

c2.c: In function ‘main’: c2.c:9:43: error: expected ‘)’ before ‘ping’ strcpy(command,"gnome-terminal -e 'sh -c "ping -c4 google.com"'");

How can I solve this?

1 Answer 1

7

You would either have to escape the inner double quotes:

strcpy(command, "gnome-terminal -e 'sh -c \"ping -c4 google.com\"'");

or directly run the ping command in the terminal, without an enclosing shell:

strcpy(command, "gnome-terminal -e 'ping -c4 google.com'");

Please note that both variants will close the terminal window immediately after the ping command exits, because neither of them starts an interactive shell.


If you want the terminal to stay open and be able to enter commands, you must start an interactive shell after ping exits. I don't know why you pick sh (which points to /bin/dash in Ubuntu) instead of the standard Bash shell with more features, but that doesn't matter. Here's how you could do it:

strcpy(command, "gnome-terminal -e 'sh -c \"ping -c4 google.com ; sh\"'");

If you just want the window to stay open until it receives a keystroke (will not allow entering a command but exit immediately when you hit any key), you would run Bash's read command after your ping, e.g. like this:

strcpy(command, "gnome-terminal -e 'bash -c \"ping -c4 google.com ; read -s -n1\"'");

This suppresses the entered key from being echoed in the terminal and returns after the first entered character, not waiting for the Enter key. For more info about read type help read in a Bash shell.

Please note that this does not work in sh (Dash) because read is specific to Bash.

4
  • strcpy(command, "gnome-terminal -e 'sh -c \"ping -c4 google.com\"'"); strcpy(command, "gnome-terminal -e 'ping -c4 google.com'"); Both commands close window, I want to prevent, to close the window after ping command exits.
    – SuperKrish
    Sep 16, 2016 at 6:11
  • Do you want to have an interactive shell prompt after ping exited, or do you just want the window to stay open without being able to enter commands?
    – Byte Commander
    Sep 16, 2016 at 12:06
  • I edited my answer to include options for both cases, but the second one requires you to use Bash.
    – Byte Commander
    Sep 16, 2016 at 12:18
  • It works awesome , you are Great Byte Commander
    – SuperKrish
    Sep 17, 2016 at 14:18

Not the answer you're looking for? Browse other questions tagged .