Linux中的骚宏

echo $?

在进行源代码编译,或者执行命令无法确认所执行的命令是否成功执行的情况下,可以使用 echo $? 来进行测试。

如果返回值是0,就是执行成功;如果是返回值是0以外的值,就是失败。

当一个进程执行完毕时,该进程会调用一个名为 _exit 的例程来通知内核它已经做好“消亡”的准备了。该进程会提供一个退出码(一个整数)表明它准备退出的原因。按照惯例,0用来表示正常的或者说“成功”的终止。也就是说我们在执行 echo $? 时反回的值就是进程的退出码。而且,这个退出码是由刚刚执行完的进程提供给系统内核的。

container_of

/*
    用于从包含在某个结构中的指针获得结构本身的指针。(也就是通过结构体变量中某个成员的首地址
    进而获得整个结构体变量的首地址)
    @ptr:表示结构体重member的地址
    @type:表示结构体的类型
    @member:表示结构体中的成员

    其实现:
    1. 定义一个临时的数据类型与ptr相同(通过typeof( ((type *)0)->member )获得)的指针变量
       __mptr,然后用它来保存ptr的值
       pstypeofGNU C对标准C的扩展,其作用是根据变量获取变量的类型
    2. 用(char*)__mptr减去member在结构体中的偏移量,得到的就是整个结构体变量的首地址 
*/
#define container_of(ptr, type, member) ({ \
    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
     (type *)( (char *)__mptr - offsetof(type,member) );})
/*
    需要在使用gcc编译
*/
#include <stdio.h>

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

#define  container_of(ptr, type, member) ({                      \
                      const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
                       (type *)( (char *)__mptr - offsetof(type,member) );})
struct test_struct 
{
    int num;
    char ch;
    float f1;
};

int main(void)
{
    struct test_struct *test_struct;
    struct test_struct init_struct = { 12,'a',12.3 };
    char *ptr_ch = &init_struct.ch;
    test_struct = container_of(ptr_ch, struct test_struct, ch);
    printf("test_struct->num =%d\n", test_struct->num);
    printf("test_struct->ch =%c\n", test_struct->ch);
    printf("test_struct->ch =%f\n", test_struct->f1);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值