C语言 c++ php mysql nginx linux lnmp lamp lanmp memcache redis 面试 笔记 ppt 设计模式 问题 远程连接

linuc c 代码示例

 

fork的应用:

#include "stdio.h"
#include "string.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
 
#include <unistd.h>

#define Max(a,b) ({int a1=a,b1=b; a1>b1?a1:b1;})

int main()
{

    int i,j,k,*q;
    char *p="abc";
    int pids[10];
    int pid;

    q=pids;

    //printf("%d \n", getpid());
    //sleep (3);

for(i=0;i<3;i++)
{

    printf("for-%d\n",i);
    pid=fork();
    if(pid) {
        *(q++) = pid;    
    }else if(pid == 0){
        sleep(5);
        printf("child:%d \n", getpid());
        break;
    }
}
    if(pid>0)
    {
        for(i=0;i<3;i++)
        {
        //    waitpid(pids[i], NULL, 0);    
            printf("parent: %d, %d \n", getpid(),pids[i]);

        }
    }
    printf("song \n");

}

没有waitpid时输出:

有waitpid时:

 

 

pthread_create 函数示例:

#include "stdio.h"
#include "string.h"
#include "pthread.h"

void *thr_fn(void *arg)
{

sleep(15);
    printf("sub :%d \n", pthread_self());
    return NULL;
}

int main()
{
    pthread_t err;
    pthread_t ntid;

    err = pthread_create(&ntid, NULL, thr_fn, NULL);
    if (err != 0)
        printf("can't create thread: %s\n", strerror(err));
    //pthread_join(ntid,NULL);

    printf("main :%d \n", pthread_self());
sleep(16);
    return 0;


}

 

posted on 2014-10-29 22:47  思齐_  阅读(442)  评论(0编辑  收藏  举报