体会 CPU 虚拟化,同时运行许多程序
cpu.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<assert.h>
#include <unistd.h>
int main(int argc,char* argv[]){
if(argc != 2){
fprintf(stderr,"usage:cpu<string>\n");
}
char *str = argv[1];
while (1)
{
sleep(1);
printf("%s\n",str);
}
return 0;
}
程序的单个实例
进程的多个实例
./cpu A & ./cpu B & ./cpu C & ./cpu D &
运行多个实例的时候,无法通过 ctrl + c 使得进程停止。只能在另外的终端通过 kill -9 (pid) 终止进程。
mem.c
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int main(int argc,char *argv[]){
int *p = (int*)malloc(sizeof(int));
assert(p != NULL);
printf("(%d) memory address of p:%08x\n",getpid(),(unsigned long)p);
//printf("(%d) memory address of p:%08x\n",getpid(),(unsigned)p);
//cast from ‘int*’ to ‘unsigned int’ loses precision [-fpermissive]
//主要是 8 字节的指针转化为 unsigned(4字节),不符合转换的精度,
//应该转化为 unsigned long
//由此可以得知,原来的程序是在 32位的电脑上测试
*p = 0;
while (1)
{
sleep(1);
*p = *p + 1;
printf("(%d) p: %d\n",getpid(),*p);
}
return 0;
}
运行程序的一个实例
运行程序的多个实例
和书本上的结果不同,两个进程并没有表现出相同的地址
threads.c
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
volatile int counter = 0;
int loops;
void *worker(void * arg){
int i;
for(int i = 0;i < loops;i++){
counter++;
}
return NULL;
}
int main(int argc,char *argv[]){
if(argc != 2){
fprintf(stderr,"usage:threads<value>\n");
exit(1);
}
loops = atoi(argv[1]);
pthread_t p1,p2;
int ret = pthread_create(&p1,NULL,worker,NULL);
if(ret == -1){
perror("pthread_create");
exit(1);
}
ret = pthread_create(&p2,NULL,worker,NULL);
if(ret == -1){
perror("pthread_create");
exit(1);
}
pthread_join(p1,NULL);
pthread_join(p2,NULL);
printf("Final Value : %d\n",counter);
return 0;
}
每次输出得到的结果都不一样。
顺便复习一下 pthread_join()
pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
io.c
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main(void){
// int fd = open("/tmp/file",O_WRONLY | O_CREAT | O_TRUNC,S_IRWXU);
int fd = open("file.txt",O_WRONLY | O_CREAT | O_TRUNC,S_IRWXU);
assert(fd > -1);
int rc = write(fd,"hello world\n",13);
assert(rc == 13);
close(fd);
return 0;
}
程序里面的补充知识
The following symbolic constants are provided for mode:
S_IRWXU 00700 user (file owner) has read, write, and execute
permission
O_TRUNC
If the file already exists and is a regular file and the access
mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be
truncated to length 0. If the file is a FIFO or terminal device
file, the O_TRUNC flag is ignored. Otherwise, the effect of
O_TRUNC is unspecified.
//好像是如果原来文件存在,其长度就会被截断成 0