代码内容
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: mem <value>\n");
exit(1);
}
int *p;
p = malloc(sizeof(int));
assert(p != NULL);
printf("(%d) addr pointed to by p: %p\n", (int) getpid(), p);
*p = atoi(argv[1]); // assign value to addr stored in p
while (1) {
Spin(1);
*p = *p + 1;
printf("(%d) value of p: %d\n", getpid(), *p);
}
return 0;
}
wby@ubuntu:~/Documents/ostep-code-master/intro$ ./mem
usage: mem <value>
wby@ubuntu:~/Documents/ostep-code-master/intro$ ./mem a
(2503) addr pointed to by p: 0x562f242e9260
(2503) value of p: 1
(2503) value of p: 2
(2503) value of p: 3
(2503) value of p: 4
(2503) value of p: 5
^C
wby@ubuntu:~/Documents/ostep-code-master/intro$ ./mem 1
(2667) addr pointed to by p: 0x55ed75c45260
(2667) value of p: 2
(2667) value of p: 3
(2667) value of p: 4
(2667) value of p: 5
^Z
[1]+ Stopped ./mem 1
wby@ubuntu:~/Documents/ostep-code-master/intro$ ./mem 5
(2668) addr pointed to by p: 0x559a69254260
(2668) value of p: 6
代码分析
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
#include <unistd.h>
由字面意思,unistd.h是unix std的意思,是POSIX标准定义的unix类系统定义符号常量的头文件,
包含了许多UNIX系统服务的函数原型,例如read函数、write函数和getpid函数。
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: mem <value>\n");
exit(1);
}
和上一篇文章一样,判断参数数量
int *p;
p = malloc(sizeof(int));
在stdlib.h
中定义的void *malloc(size_t size)()
函数,size指字节,比如malloc(15)
就是分配15字节的内存空间
assert(p != NULL);
定义在头文件assert.h
中,判断表达式的逻辑真假,如果为false
,就会在stderr
上面打印一条包含“表达式,文件名,行号”的错误信息,然后调用abort
结束整个程序。
(在common.h
头文件中定义的)
printf("(%d) addr pointed to by p: %p\n", (int) getpid(), p);
这是printf()
函数的使用方法,%是一个格式化标志,可以是%d %p %x。 参考资料。
%p表示输出以内存中实际存储一个变量格式(十六进制、32位(视机器而定))的值。
*p = atoi(argv[1]); // assign value to addr stored in p
在C标准库<stdlib.h>
中定义的函数,把参数指向的字符串转换为一个整数(类型为int型)
例如:
字符串值 = 98993489, 整型值 = 98993489
字符串值 = xxx.com, 整型值 = 0
while (1) {
Spin(1);
*p = *p + 1;
printf("(%d) value of p: %d\n", getpid(), *p);
}
return 0;
}
循环输出