Module 19: Lập trình hệ thống

Lập trình hệ thống với C

argc và argv - Đối số dòng lệnh

int main(int argc, char *argv[]) {
    printf("Ten chuong trinh: %s\n", argv[0]);
    for (int i = 1; i < argc; i++)
        printf("Doi so %d: %s\n", i, argv[i]);
}

Biến môi trường

#include <stdlib.h>
char *path = getenv("PATH");    // lay bien moi truong
putenv("MY_VAR=hello");          // dat bien moi truong

Hệ thống file

#include <stdio.h>
remove("file.txt");     // xoa file
rename("old","new");    // doi ten
FILE *f = fopen("f.txt","r");
if (f) { /* doc file */ fclose(f); }

Process

#include <stdlib.h>
system("dir");     // chay lenh he thong (Windows)
system("ls -la");  // chay lenh he thong (Linux)

Trên Linux/Unix:

#include <unistd.h>
#include <sys/wait.h>

pid_t pid = fork();
if (pid == 0) { /* tien trinh con */ }
else { /* tien trinh cha */ wait(NULL); }

Signal handling

#include <signal.h>
void handler(int sig) { printf("Nhan signal %d\n", sig); }
signal(SIGINT, handler); // Ctrl+C