[CO004] Respuesta de referencia de parte del código del cuestionario de práctica 1 del sistema operativo

Autor: YY compañero de clase

La vida es infinita y el código es infinito. Los proyectos divertidos están todos en GitHub


PD: La prueba se ha completado en MUST-CO004 Linux y la máquina virtual local Ubuntu Linux, y es correcta. Bienvenido a proporcionar más versiones de prueba en otros entornos de Linux

1. [Fácil] El proceso hijo ejecuta el comando who

Por favor, escriba un programa en C que creará un proceso hijo: child1. Child1 ejecutará un comando "quién".

Salida de muestra:

henry
s14F047
s14G059
s14G173
s14J056
s14U028

Solución:

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

int main(){
    
    
	// 这样写严格意义上有可能会产生 Zombie,但是不违反题目要求
	int child1 = fork();
	if(child1 == 0){
    
    
		execl("/bin/who","who",NULL);
	}
	return 0;
}

2. [Fácil] Problema de espera del proceso entre padres e hijos

Escriba un programa en C para crear un proceso hijo utilizando fork (). En su programa, el proceso padre (el programa en sí) terminará después de que el proceso hijo esté muerto. Utilice wait () o waitpid () para lograr este objetivo.

Salida de muestra:

The child process with PID 1235 terminated
The parent process with PID 1234 terminated

Solución:

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

int main(){
    
    
    int pid_child = fork();
    int status; // 这里需要自己定义 status 参数,因为题目明确要求要用 waitpid() 
    if( pid_child !=0 ){
    
    
        waitpid(pid_child,&status,0);
        printf("The parent process with PID: %d terminated\n", getpid());
    }
    else{
    
    
        printf("The child process with PID: %d terminated\n", getpid());
    }
    return 0;
}

3. [Fácil] Calcule y produzca los procesos padre e hijo por separado.

Complete un programa en C que use el proceso hijo para calcular sumas y el padre para calcular los productos de una matriz de 5 enteros. Genere también los PID del niño y del padre, respectivamente.
La matriz dada: int A [] = {1,2,3,4,5};

Salida de muestra:

The child process with PID 2345 and the computed sum is 15.
The parent process with PID 2344 and the computed product is 120.

Solución:

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

int main(){
    
    
    int A[]={
    
    1,2,3,4,5};
    int pid_child = fork();
    if( pid_child !=0 ){
    
    
        wait(NULL);
        int product=1;
        int i; // 注意在 C99 编译环境下不允许在 for 循环内部定义变量 i,所以需要定义在外面
        for(i=0; i <5;++i) {
    
    product*=A[i];}
        printf("The parent process with PID: %d and the computed product is %d.\n", getpid(), product);
    }
    else{
    
    
    	int sum=0;
		int i;
    	for(i=0; i <5;++i) {
    
    sum+=A[i];}
        printf("The child process with PID: %d and the computed sum is %d.\n", getpid(), sum);
    }

    return 0;
}

4. [Fácil] Juicio del tamaño del parámetro digital

Escriba un script de shell Bash llamado condition.sh para verificar si el argumento de entrada (es decir, un número entero) es mayor que 100, menor que 100 o igual a 100. Sugerencia, necesita usar la instrucción if o else.

Salida de muestra:

$./condition.sh 150
The number is larger than 100
$./condition.sh 90
The number is smaller than 100
$./condition.sh 100
The number is equal to 100

Solución:

#!/bin/bash

# 注意题目要求是读取参数而非读取用户输入的数字,所以这里要用 $1 代表第一个参数
if [ $1 -gt 100 ]; then                         
    echo "The number is larger than 100"
elif [ $1 -lt 100 ]; then 
	echo "The number is smaller than 100"
else
	echo "The number is equal to 100"
fi

5. 【Normal】 Número de palabras

Escriba un script de shell Bash llamado filesearch.sh para calcular el número de la palabra "the" en cada línea y el archivo completo del archivo dado.

tinyTale.txt

it was the best of times it was the worst of times
it was the age of wisdom it was the age of foolishness
it was the epoch of belief it was the epoch of incredulity
it was the season of light it was the season of darkness
it was the spring of hope it was the winter of despair

Salida de muestra:

./filesearch.sh tinyTale.txt
Line 1 contains 2 "the".
Line 2 contains 2 "the".
Line 3 contains 2 "the".
Line 4 contains 2 "the".
Line 5 contains 2 "the".
File tinyTale.txt contains 10 "the".

Solución:

#!/bin/bash

read source

index=0
sum=0

while read line
do
	index=$((index+1))
	count=0

	for word in ${line}; do
    	if [ $word == 'the' ]; then
    		(( count++ ))
    	fi
    done
        
    echo "Line ${index} contains ${count} \"the\"."
    
    (( sum+=count ))

done < ${source} # 感谢 zsj 大佬提醒:由于管道循环内部无法改变外部变量,因此需要采取重定向解决方案

echo "File ${source} contains ${sum} \"the\"."

Una solución breve y factible: (proporcionada por cyyyyxxxx )


awk -v awkvar='Line' -v awkvar1='contains', -v awkvar2='"the"' -F'the' 'NF{print(awkvar,NR,awkvar1,NF-1,awkvar2)}' tinyTale.txt

a=$(grep -o "the" tinyTale.txt | wc -l)
echo File tinyTale.txt contains $a '"the"'

Supongo que te gusta

Origin blog.csdn.net/qq_42950838/article/details/114953288
Recomendado
Clasificación