传递参数来运行C app

时间:2014-06-29 20:38:35

标签: c linux command-line-arguments

我正在编写小型C程序,它将像守护进程一样,每秒都做一些事情。我管理它只使用filelock运行单个实例,我需要知道的最后一件事是,是否可以将命令行参数发送到正在运行的程序,如下所示:

第一个程序开始:

./sampleprogram

然后决定采取一些行动/更新设置

./sampleprogram -r

这将是我的thinkpad X41敞篷车的另一个​​旋转脚本:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
/*#include <stdbool.h>*/
#define TRUE 1
#define FALSE 0
#define NIL -1

int fdlock;
int get_lock(void)
{
    struct flock fl;
    fl.l_type = F_WRLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 1;
    if((fdlock = open("oneproc.lock", O_WRONLY|O_CREAT, 0666)) == -1) { return 0; }
    if(fcntl(fdlock, F_SETLK, &fl) == -1) { return 0; }
    return 1;
}


int main() {

    if(!get_lock()) {
        fputs("Process already running!\n", stderr);
        return 1;
    }

    int tabletmode;
    int autorotate = TRUE;
    int prevmode = NIL;
    FILE *fstate;
    char state[1];
    FILE *fgyrovals;
    char gyroval_a[1];

    while (TRUE) {
        fstate = fopen("/sys/devices/platform/thinkpad_acpi/hotkey_tablet_mode", "r");
        fread(state, sizeof(state[0]), 1, fstate);
        /*
        printf("picaa");
        fflush(stdout);
        */
        /*tabletmode = atoi(state[0]);*/
        tabletmode = state[0] - '0';
        printf("koko: %d", tabletmode);
        fflush(stdout);
        fclose(fstate);

        if (prevmode != tabletmode) {
            if (tabletmode) {
                system("notify-send 'Notebook v tablet móde'");
            } else {
                system("notify-send 'Notebook v štandartnom režime'");
            }
        }

        if (tabletmode) {
            if (autorotate) {
                fgyrovals = fopen("/sys/devices/platform/hdaps/position", "r");
                fclose(fgyrovals);
            }
        }           

        prevmode = tabletmode;

        sleep(1);
    }
    return 0;
}

0 个答案:

没有答案