等待子进程

Posted on 2012年9月06日 15:56
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    pid_t pid;
    char *message;
    int n;
    int exit_code;

    printf("fork program starting\n");
    pid = fork();

    switch(pid)
    {
        case -1:
            perror("fork failed");
            exit(1);
        case 0:
            message = "This is the child";
            n = 5;
            exit_code = 37;
            break;
        default:
            message = "This is the parent";
            n = 3;
            exit_code = 0;
            break;
    }

    for (; n > 0; n--)
    {
        puts(message);
        sleep(1);
    }

    if (pid != 0)
    {
        int stat_val;
        pid_t child_pid;
        child_pid = wait(&stat_val);
        printf("Child has finished: PID = %d\n", child_pid);
        if (WIFEXITED(stat_val))
            printf("Child exited with code %d\n", WEXITSTATUS(stat_val));
        else
            printf("Child terminated abnormally\n");
    }

    exit(exit_code);
}

ubuntu mysql 接口

Posted on 2012年9月03日 15:17

先安装MySQL
代码:
sudo apt-get install mysql-server mysql-client

再装开发包
代码:
sudo apt-get install libmysqlclient15-dev

安装完以后,C代码里添加头文件

代码:
#include <mysql.h>

编译方法:
代码:
gcc $(mysql_config --cflags) xxx.c -o xxx $(mysql_config --libs)

dbm

Posted on 2012年9月02日 21:01

ubuntu 安装 ndbm

先安装gdbm:sudo apt-get install libgdbm-dev
程序中使用:gdbm-ndbm.h
编译:gcc -o dbm1 dbm1.c -lgdbm_compat -lgdbm

 

示例一:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <gdbm-ndbm.h>
#include <string.h>

#define TEST_DB_FILE "/tmp/dbm1_test"
#define ITEMS_USED 3

struct test_data {
    char misc_chars[15];
    int any_integer;
    char more_chars[21];
};

int main()
{
    struct test_data items_to_store[ITEMS_USED];
    struct test_data item_retrieved;

    char key_to_use[20];
    int i, result;

    datum key_datum;
    datum data_datum;

    DBM *dbm_ptr;
    dbm_ptr = dbm_open(TEST_DB_FILE, O_RDWR | O_CREAT, 0666);
    if (!dbm_ptr)
    {
        fprintf(stderr, "Failed to open database.\n");
        exit(EXIT_FAILURE);
    }
    memset(items_to_store, '\0', sizeof(items_to_store));
    strcpy(items_to_store[0].misc_chars, "First!");
    items_to_store[0].any_integer = 47;
    strcpy(items_to_store[0].more_chars, "foo");

    strcpy(items_to_store[1].misc_chars, "bar");
    items_to_store[1].any_integer = 13;
    strcpy(items_to_store[1].more_chars, "unlucky?");

    strcpy(items_to_store[2].misc_chars, "Third");
    items_to_store[2].any_integer = 3;
    strcpy(items_to_store[2].more_chars, "baz");

    for (i = 0; i < ITEMS_USED; i++)
    {
        sprintf(key_to_use, "%c%c%d",
                items_to_store[i].misc_chars[0],
                items_to_store[i].more_chars[0],
                items_to_store[i].any_integer);
        key_datum.dptr = (void *)key_to_use;
        key_datum.dsize = strlen(key_to_use);
        data_datum.dptr = (void *)&items_to_store[i];
        data_datum.dsize = sizeof(struct test_data);

        result = dbm_store(dbm_ptr, key_datum, data_datum, DBM_REPLACE);
        if (result != 0)
        {
            fprintf(stderr, "dbm_store failed on key %s\n", key_to_use);
            exit(2);
        }
    }

    sprintf(key_to_use, "bu%d", 13);
    key_datum.dptr = key_to_use;
    key_datum.dsize = strlen(key_to_use);

    data_datum = dbm_fetch(dbm_ptr, key_datum);
    if (data_datum.dptr)
    {
        printf("Data retrieved\n");
        memcpy(&item_retrieved, data_datum.dptr, data_datum.dsize);
        printf("Retrieved item - %s %d %s\n",
                item_retrieved.misc_chars,
                item_retrieved.any_integer,
                item_retrieved.more_chars);
    }
    else
    {
        printf("No data found for key %s\n", key_to_use);
    }
    dbm_close(dbm_ptr);
    exit(EXIT_SUCCESS);
}

示例二

 

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <gdbm-ndbm.h>
#include <string.h>

#define TEST_DB_FILE "/tmp/dbm2_test"
#define ITEMS_USED 3

struct test_data {
    char misc_chars[15];
    int any_integer;
    char more_chars[21];
};

int main()
{
    struct test_data items_to_store[ITEMS_USED];
    struct test_data item_retrieved;

    char key_to_use[20];
    int i, result;

    datum key_datum;
    datum data_datum;

    DBM *dbm_ptr;
    dbm_ptr = dbm_open(TEST_DB_FILE, O_RDWR | O_CREAT, 0666);
    if (!dbm_ptr)
    {
        fprintf(stderr, "Failed to open database.\n");
        exit(EXIT_FAILURE);
    }
    memset(items_to_store, '\0', sizeof(items_to_store));
    strcpy(items_to_store[0].misc_chars, "First!");
    items_to_store[0].any_integer = 47;
    strcpy(items_to_store[0].more_chars, "foo");

    strcpy(items_to_store[1].misc_chars, "bar");
    items_to_store[1].any_integer = 13;
    strcpy(items_to_store[1].more_chars, "unlucky?");

    strcpy(items_to_store[2].misc_chars, "Third");
    items_to_store[2].any_integer = 3;
    strcpy(items_to_store[2].more_chars, "baz");

    for (i = 0; i < ITEMS_USED; i++)
    {
        sprintf(key_to_use, "%c%c%d",
                items_to_store[i].misc_chars[0],
                items_to_store[i].more_chars[0],
                items_to_store[i].any_integer);
        key_datum.dptr = (void *)key_to_use;
        key_datum.dsize = strlen(key_to_use);
        data_datum.dptr = (void *)&items_to_store[i];
        data_datum.dsize = sizeof(struct test_data);

        result = dbm_store(dbm_ptr, key_datum, data_datum, DBM_REPLACE);
        if (result != 0)
        {
            fprintf(stderr, "dbm_store failed on key %s\n", key_to_use);
            exit(2);
        }
    }

    sprintf(key_to_use, "bu%d", 13);
    key_datum.dptr = key_to_use;
    key_datum.dsize = strlen(key_to_use);
    
    if (dbm_delete(dbm_ptr, key_datum) == 0)
    {
        printf("Data with key %s deleted\n", key_to_use);
    }
    else
    {
        printf("Nothing deleted for key %s\n", key_to_use);
    }

    for (key_datum = dbm_firstkey(dbm_ptr);
         key_datum.dptr;
         key_datum = dbm_nextkey(dbm_ptr)) 
    {    
        data_datum = dbm_fetch(dbm_ptr, key_datum);
        if (data_datum.dptr)
        {
            printf("Data retrieved\n");
            memcpy(&item_retrieved, data_datum.dptr, data_datum.dsize);
            printf("Retreved item - %s %d %s\n",
                    item_retrieved.misc_chars,
                    item_retrieved.any_integer,
                    item_retrieved.more_chars);
        }
        else
        {
            printf("No data found for key %s\n", key_to_use);
        }
    }

    dbm_close(dbm_ptr);
    exit(EXIT_SUCCESS);
}

 

with 上下文管理器

Posted on 2012年8月31日 01:04
#!/usr/bin/env python3

class ListTransaction:
    
    def __init__(self, theList):
        self.theList = theList

    def __enter__(self):
        self.workingcopy = list(self.theList)
        return self.workingcopy

    def __exit__(self, type, value, tb):
        if type is None:
            self.theList[:] = self.workingcopy
        return False

 

#!/usr/bin/env python3

from contextlib import contextmanager

@contextmanager
def ListTransaction(thelist):
    workingcopy = list(thelist)
    yield workingcopy
    # only do not raise error 
    thelist[:] = workingcopy

termios示例之不回显字符

Posted on 2012年8月26日 15:27
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>

#define PASSWORD_LEN 8

int main()
{
    struct termios initialrsettings, newrsettings;
    char password[PASSWORD_LEN + 1];

    tcgetattr(fileno(stdin), &initialrsettings);
    newrsettings = initialrsettings;
    newrsettings.c_lflag &= ~ECHO;

    printf("Enter password: ");

    if (tcsetattr(fileno(stdin), TCSAFLUSH, &newrsettings) != 0)
    {
        fprintf(stderr, "Could not set attributes\n");
    }
    else
    {
        fgets(password, PASSWORD_LEN, stdin);
        tcsetattr(fileno(stdin), TCSANOW, &initialrsettings);
        fprintf(stdout, "\nYou entered %s\n", password);
    }

    exit(0);
}           

Enter password:
You entered 123456
 

环境变量之environ

Posted on 2012年8月23日 21:32

environ字符串数组保存了所有环境变量

 

#include <stdlib.h>
#include <stdio.h>

extern char **environ;

int main()
{
    char **env = environ;

    while (*env)
    {
        printf("%s\n", *env);
        env++;
    }

    exit(0);
}

环境变量之getenv、putenv

Posted on 2012年8月23日 21:22
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char *var, *value;

    if (argc == 1 || argc > 3)
    {
        fprintf(stderr, "usage: environ var[value]\n");
        exit(1);
    }

    var = argv[1];
    value = getenv(var);
    if (value)
        printf("Variable %s has value %s\n", var, value);
    else
        printf("Variable %s has no value\n", var);

    if (argc == 3)
    {
        char *string;
        value = argv[2];
        string = malloc(strlen(var) + strlen(value) + 2);
        if (!string)
        {
            fprintf(stderr, "out of memory!\n");
            exit(1);
        }
        strcpy(string, var);
        strcat(string, "=");
        strcat(string, value);
        printf("Calling putenv with: %s\n", string);
        if (putenv(string) != 0)
        {
            fprintf(stderr, "putenv failed\n");
            free(string);
            exit(1);
        }

        value = getenv(var);
        if (value)
            printf("New value of %s is %s\n", var, value);
        else
            printf("New value of %s is null??\n", var);
    }

    exit(0);
}

注意:环境仅对程序本身有效,你在程序里做的改变不会反映到外部环境中,这是因为变量的值不会从子进程(你的程序)传播到父进程(shell)。

getopt_long

Posted on 2012年8月22日 15:50
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define _GNU_SOURCE
#include <getopt.h>

int main(int argc, char *argv[])
{
    int opt;
    struct option longopts[] = {
        {"initialize", 0, NULL, 'i'},
        {"file", 1, NULL, 'f'},
        {"list", 0, NULL, 'l'},
        {"restart", 0, NULL, 'r'},
        {0, 0, 0, 0}
    };

    while ((opt = getopt_long(argc, argv, ":if:lr", longopts, NULL)) != -1)
    {
        switch (opt)
        {
            case 'i':
            case 'l':
            case 'r':
                printf("option: %c\n", opt);
                break;
            case 'f':
                printf("filename: %s\n", optarg);
                break;
            case ':':
                printf("option needs a value\n");
                break;
            case '?':
                printf("unkown option: %c\n", optopt);
                break;
        }
    }

    for (; optind < argc; optind++)
    {
        printf("argument: %s\n", argv[optind]);
    }

    exit(0);
}

递归列出某目录下所有目录

Posted on 2012年8月21日 15:34
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

void printdir(char *dir, int depth)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;

    if ((dp = opendir(dir)) == NULL)
    {
        fprintf(stderr, "can not open directory: %s\n", dir);
        return;
    }
    chdir(dir);
    while ((entry = readdir(dp)) != NULL)
    {
        lstat(entry->d_name, &statbuf);
        if (S_ISDIR(statbuf.st_mode))
        {
            /* Found a directory, but ignore . and .. */
            if (strcmp(".", entry->d_name) == 0 ||
                strcmp("..", entry->d_name) == 0)
                continue;
            printf("%*s%s\n", depth, " ", entry->d_name);
            sleep(1);    // 手贱休眠一秒
            /* Recurse at new indent level */
            printdir(entry->d_name, depth + 4);
        }
    }
    chdir("..");
    closedir(dp);
}

int main(int argc, char *argv[])
{
    char *topdir = ".";
    if (argc >= 2)
        topdir = argv[1];
    printf("Directory scan of %s\n", topdir);
    printdir(topdir, 0);
    printf("done.\n");

    exit(0);
}

【转】免费电子书列表

Posted on 2012年8月12日 15:49

在StackOverflow上,有人要打算收集个免费电子书的列表,结果很快就有人分享了一个列表。很不错,我就转过来了。

 

原帖的地址在http://stackoverflow.com/questions/194812/list-of-freely-available-programming-books (注意:有些连接可能会被墙掉)

 

List of Free Programming books (compiled): Meta-List

Graphics Programming

Language Agnostic

ASP.NET MVC:

Assembly Language

Bash

C/C++

C#

  • See .NET below

Django

Forth

Git

Haskell

Java

JavaScript

Linux

Lisp

Lua

Maven

Mercurial

.NET (C#)

NoSQL

Objective-C

Parrot / Perl 6

Perl

PHP

PowerShell

Prolog

PostgreSQL

Python

Ruby

Scala

Scheme

SmallTalk

Subversion

*SQL (Implementation agnostic) *