linux下c編程入門筆記

來源:互聯網
上載者:User

標籤:io   ar   os   使用   sp   for   檔案   on   2014   

一、基礎知識來源程式編譯

/***hello.c***/

int main() {printf("hello,world.\n"); return 0;}

gcc -o hello hello.c

-o產生可執行檔

-c只輸出目標代碼

-g可調試

makefile編寫

####makefile1####

main: main.o t1.o t2.o

  gcc -o [email protected] $^

main.o: main.c t1.h t2.h

  gcc -c $<

t1.o: t1.c t1.h

  gcc -c $<

t2.o: t2.c t2.h

  gcc -c $<

[email protected]##目標檔案

$^##所有依賴檔案

$<##第一個依賴檔案

####makefile2####

main: main.o t1.o t2.o

  gcc -o [email protected] $^

..c.o

  gcc -c $<

##自動推導

程式庫的串連

-lm數學庫

-lpthread線程庫

系統的預設庫路徑:/lib, /usr/lib, /usr/local/lib

否則要指定串連路徑:-L/home/ming/mylibs -lming 這樣就會到相應目錄下串連libming.so|libming.a

調試

參考gdb入門

協助

man write ###write命令的協助

man 2 write ###系統調用函數的協助

man 3 write ###C庫函數的協助

二、進程進程概念

進程是程式的執行過程,即一個開始執行但沒有結束的程式的執行個體。每個進程可以有多個子進程...

為了區分不同的進程,系統給每個進程分配了唯一的id以示區別

進程的狀態:建立、運行、阻塞、就緒、完成

個人理解:linux下的多線程根本上都是多個子進程,分別擁有自己的進程id,但沒有自己的進程名,與之對應的父進程的程式名。

查看進程命令:ps, 如:ps -ef, ps -aux

進程的標誌

#include <unistd.h>

pid_t getpid();//獲得進程id

pid_t getppid();//獲得父進程id

進程是為程式服務的,程式是為使用者服務的。系統為了找到進程的使用者名稱,為進程和使用者建立了聯絡。這個使用者成為進程的所有者,相應的每個使用者也有一個使用者id。使用者隸屬不同的組,每個組也有自己的id。

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

uid_t getuid();//獲得進程所有者使用者id

uid_t geteuid();//獲得進程的有效使用者id

gid_t getgid();//獲得組id

gid_t getegid();//獲得有效組id

進程的建立

#include<unistd.h>

pid_t fork();//建立進程

對於父進程fork()返回子進程的id,對於fork子進程返回0,建立進程失敗返回-1。一旦子進程被建立,就與父進程一起從fork處繼續執行,相互競爭系統的資源。如果希望子進程執行,而父進程阻塞直到子進程完成,這是可以調用wait()或waitpid()函數。

父進程建立子進程後,子進程一般要調用不同的程式。為了調用系統程式,可以使用如下的exec族的函數:

#include<unistd.h>

int execl(char*path,char*arg,...);

int execlp(char*file,char*arg,...);

int execle(char*path,char*arg,...);

int execv(char*path,char*argv[]);

int execvp(char*file,char*argv[]);

/********forktest.c**********/

#include<unistd.h><sys/types.h><sys/wait.h><stdio.h><errno.h><math.h>

void main()

{

  pid_t child;

  int status;

  if((child = fork()) == -1) exit(1);

  else if(child == 0)

  {

    int i;

    printf("i am the child: %ld\n", getpid());

    for(i=0; i<1000000; i++) sin(i);

    exit(5);

  }

  while(((child=wait(&status))==-1)&&(errno==EINTR));

  if(child == -1)printf("wait error: %s\n", strerror(errno));

  else if(!status);

  else {...}

}

守護進程

/****checkmail.c****/

#include<unistd.h><sys/types.h><sys/stat.h><stdio.h><errno.h><fcntl.h><signal.h>

#define MAIL "/var/spool/mail/ming"

#define SLEEP_TIME 10

void main()

{

  pid_t child;

  if((child=fork())==-1)exit(1);

  else if(child>0)while(1);

  if(kill(getppid(),SIGTERM)==-1)exit(1);

  int mailfd;

  while(1)

  {

    mailfd=open(MAIL,O_RDONLY);

    close(mailfd);

    sleep(SLEEP_TIME);

  }

}

三、檔案操作檔案讀寫

/*****filerw.h****/

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <sting.h>
#define BUF_SIZE 1024
int main(int argc, char** argv)
{
    int from_fd, to_fd;
    int bytes_read, bytes_write;
    char buf[BUF_SIZE];
    char* ptr;
    if(argc != 3) {
        fprintf(stderr, "Usage: %s fromfile tofile \n\a", argv[0]);
        exit(1);
    }
    if((from_fd = open(argv[1], O_RDONLY)) == -1) exit(1);
    if((to_fd = open(argv[2], O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR)) == -1) exit(1);
    while(bytes_read = read(from_fd, buf, BUF_SIZE))
    {
        if((bytes_read = -1) && (errno != EINTR)) break;
        else if(bytes_read > 0) {
            ptr = buf;
            while(bytes_write = write(to_fd, ptr, bytes_read))
            {
                if((bytes_write == -1) && (errno != EINTR)) break;
                else if(bytes_write == bytes_read) break;
                else if(bytes_write > 0) {
                    ptr += bytes_write;
                    bytes_read -= bytes_write;
                }
                if(bytes_write == -1) break;
            }
        }
    }
    close(from_fd);
    close(to_fd);
    return 0;
}

目錄操作

/******dir_opt.c********/
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>

static int get_file_size_time(const char* filename)
{
    struct stat statbuf;
    if(stat(filename, &statbuf) == -1) return -1;
    if(S_ISDIR(statbuf.st_mode)) return 1;
    if(S_ISREG(statbuf.st_mode)) {
        printf("%s size: %ldbytes \t modified at %s \n", filename, statbuf.st_size, ctime(&statbuf.st_mtime));
    }
    return 0;
}
int main(int argc, char** argv)
{
    DIR* dirp;
    struct dirent* direntp;
    int stats;
    if(argc != 2) {
        printf("Usage: %s filename \n\a", argv[0]);
        exit(1);
    }
    if(((stats = get_file_size_time(argv[1])) == 0) || (stats == -1)) exit(1);
    if((dirp = opendir(argv[1])) == NULL) {
        exit(1);
    }
    while((direntp = readdir(dirp)) != NULL);
    closedir(dirp);
    return 0;
}

管道檔案

/********pipe.c*********/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFFER 255

int main(int argc, char** argv)
{
    char buffer[BUFFER+1];
    int fd[2];
    if(argc != 2) {
        fprintf(stderr, "Usage: %s string\n\a", argv[0]);
        exit(1);
    }
    if(pipe(fd) != 0) exit(1);
    if(fork() == 0) {
        close(fd[0]);
        printf("child[%d] write to pipe. \n", getpid());
        snprintf(buffer, BUFFER, "%s", argv[1]);
        write(fd[1], buffer, strlen(buffer));
        printf("child[%d] quit. \n", getpid());
        exit(0);
    }
    else {
        close(fd[1]);
        printf("parent[%d] read from pipe \n", getpid());
        memset(buffer, 0, BUFFER+1);
        read(fd[0], buffer, BUFFER);
        printf("parent[%d] read: %s\n", getpid(), buffer);
        exit(1);
    }
    return 0;
}

四、時間時間表示

#include <sys/time.h>

time_t time(time_t* tloc);//返回1970年至今的秒數

char* ctime(const time_t* clock);//返回類似"Fri Nov 7 13:40:58 2014"字串

gettimeofday();//獲得一天內的時間

計時器

todo......

五、訊號處理

todo

六、訊息管理

todo

七、線程操作

子進程是通過拷貝父進程的地址空間來執行的,線程是通過共用程式碼來執行的。

-lpthread連接線程庫

#include <pthread.h>

int pthread_create(pthread_t* thread, pthread_attr_t* attr, void*(*start_routine)(void*), void* arg);

void pthread_exit(void* retval);

int pthread_join(pthread* thread, void** thread_return);

八、網路編程

todo

 

linux下c編程入門筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.