Detach process to start firefox in C

183 views Asked by At

The point of this C program is to make it easier for me to open websites that correspond to each of my classes at school. The code generally works perfectly when I run it in my terminal (kitty), but it fails when I bind it to a key.

I am on Linux, and I'm binding keys with XFCE4's default keybind utility. My keybind opens the executable in my terminal emulator, kitty.

On my setup, I bound PageUp to the following command:

kitty bash -c "/home/carter/Code/classes/classes"

It should do the following (in order):

  1. display a list of classes I can choose from
  2. ask for a number from 1-7
  3. open the link for the corresponding class in firefox
  4. stop executing and allow kitty to close

Here's the code (I've changed the links and class names to examples for anonymity):

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

int main() {
    char classNames[7][15] = {"Class 1", "Class 2", "Class 3", "Class 4", "Class 5", "Class 6", "Class 7"};
    char classLinks[7][60] = {"http://class1.com", "http://class2.com", "http://class3.com", "http://class4.com", "http://class5.com", "http://class6.com", "http://class7.com"};
    
    for (int i = 0; i < sizeof(classNames)/15; i++) { // 15 bytes to each string
        printf("%d) ", i+1);
        printf(classNames[i]);
        printf("\n");
    }

    int classIndex;
    printf("\nClasses to open: ");
    
    scanf("%d", &classIndex);  

    char cmd[70];

    strcpy(cmd, "firefox ");
    strcat(cmd, classLinks[classIndex-1]);
    //strcat(cmd, " &"); // spawn new process ?
    
    printf(cmd);
    printf("\n");

    system(cmd);
    //popen(cmd, "w") // ???
}

Here's some things I've tried (remember, I'm pretty sure all of these work when executing them directly in the terminal. They break when I try to bind the executable to a key):

  1. running the command in the format firefox {URL} with system()

This seems to work at first, but it leaves my terminal window open after the code is done executing. When I close kitty, it closes firefox.

  1. running it in the format firefox {URL} & to spawn a new process using system()

This does not work. It displays the classes and reads my input correctly, but it fails to do anything afterwards. Firefox does not open, kitty closes.

  1. running it like popen("firefox {URL}", "w")

When I do this, I get the same results as #2.

I'm trying to get some kind of system call to correctly spawn a new firefox process. Any idea what's going on? Sorry for all that background information.

1

There are 1 answers

0
Carter Prince On

Nevermind. After some fiddling, I found a solution that worked for me.

I ended up using the setsid command with the f flag:

strcpy(cmd, "setsid -f firefox ");
strcat(cmd, classLinks[classIndex-1]);