добавлены исходники на c, cpp, java, nasm, perl, php, ruby, prolog, nasm
This commit is contained in:
parent
de6d752b16
commit
290a99e0ee
|
@ -1,19 +1,19 @@
|
|||
#!/bin/bash
|
||||
|
||||
echo $0
|
||||
|
||||
|
||||
#n=0
|
||||
#until [ $n -eq 4 ]; do
|
||||
# echo $n
|
||||
# let n=n+1
|
||||
#done
|
||||
|
||||
n=0
|
||||
until [ $n -eq 4 ]; do
|
||||
echo $n
|
||||
let n=n+1
|
||||
done
|
||||
|
||||
n=0
|
||||
while [ ! $n -eq 4 ]; do
|
||||
echo $n
|
||||
let n=n+1
|
||||
done
|
||||
#n=0
|
||||
#while [ ! $n -eq 4 ]; do
|
||||
# echo $n
|
||||
# let n=n+1
|
||||
#done
|
||||
|
||||
|
||||
# #Стирает все пустые файлы
|
||||
|
@ -33,7 +33,7 @@ done
|
|||
#done
|
||||
|
||||
|
||||
#for item in `cat amd64dirs`
|
||||
#for item in `cat backbonedirs`
|
||||
#do
|
||||
# echo $item
|
||||
#done
|
||||
|
@ -91,7 +91,7 @@ done
|
|||
|
||||
#if (true) #[echo trigger.dat];
|
||||
#then
|
||||
#./mount_amd64.run
|
||||
#./mount_backbone.run
|
||||
# echo "ON"
|
||||
# echo -n 0 > trigger.dat
|
||||
#fi
|
||||
|
@ -99,7 +99,7 @@ done
|
|||
# echo "OFF"
|
||||
#fi
|
||||
#else
|
||||
#./umount_amd64.run
|
||||
#./umount_backbone.run
|
||||
# echo "OFF"
|
||||
# echo -n 1 > trigger.dat
|
||||
#elif
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
#!/bin/bash
|
||||
# Чтение строк из файла /etc/fstab.
|
||||
|
||||
File=/etc/fstab
|
||||
|
||||
{
|
||||
read line1
|
||||
read line2
|
||||
} < $File
|
||||
|
||||
echo "Первая строка в $File :"
|
||||
echo "$line1"
|
||||
echo
|
||||
echo "Вторая строка в $File :"
|
||||
echo "$line2"
|
||||
|
||||
exit 0
|
|
@ -0,0 +1,85 @@
|
|||
#include <sys/time.h>
|
||||
#include <time.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
|
||||
#define TIME_CYCLE_SEC 10
|
||||
|
||||
typedef unsigned long long ull;
|
||||
|
||||
static ull max_wait_time = 0;
|
||||
|
||||
void termination_handler (int signum) {
|
||||
if(signum == SIGINT) {
|
||||
printf("----------------------------\n");
|
||||
printf("Тест окончен!\n");
|
||||
printf ("Максимальная задержка за всё время = %llu микросекунд\n", max_wait_time);
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
int max_wait_test() {
|
||||
|
||||
signal(SIGINT, termination_handler);
|
||||
|
||||
struct timezone tz;
|
||||
tz.tz_minuteswest = 0;
|
||||
tz.tz_dsttime = 0;
|
||||
|
||||
struct timeval tv;
|
||||
|
||||
gettimeofday(&tv, &tz);
|
||||
ull last_time = ((ull)tv.tv_sec) * 1000000 + (ull)tv.tv_usec;
|
||||
ull start_tv_sec = (ull)tv.tv_sec;
|
||||
ull last_tv_sec = start_tv_sec;
|
||||
ull average_wait_time = 0;
|
||||
|
||||
while( 1 == 1 ) {
|
||||
|
||||
gettimeofday(&tv, &tz);
|
||||
|
||||
ull mcs = ((ull)tv.tv_sec) * 1000000 + (ull)tv.tv_usec;
|
||||
|
||||
ull delta_time = mcs - last_time;
|
||||
|
||||
if(delta_time > max_wait_time)
|
||||
max_wait_time = delta_time;
|
||||
|
||||
if(delta_time > average_wait_time)
|
||||
average_wait_time = delta_time;
|
||||
|
||||
|
||||
// noop на несколько наносекунд
|
||||
struct timespec wait_ts;
|
||||
wait_ts.tv_sec = 0;
|
||||
wait_ts.tv_nsec = 10;
|
||||
nanosleep(&wait_ts,NULL);
|
||||
|
||||
// Выводим каждые TIME_CYCLE_SEC секунд среднюю задержку за эти TIME_CYCLE_SEC секунд
|
||||
if(last_tv_sec + TIME_CYCLE_SEC <= tv.tv_sec) {
|
||||
printf("----------------------------\n");
|
||||
printf("Время выполнения = %llu секунд\n", last_tv_sec - start_tv_sec);
|
||||
printf("Максимальная задержка за %d секунд = %llu микросекунд\n", TIME_CYCLE_SEC, average_wait_time);
|
||||
printf ("Максимальная задержка за всё время = %llu микросекунд\n", max_wait_time);
|
||||
fflush(stdout);
|
||||
gettimeofday(&tv, &tz);
|
||||
last_tv_sec = tv.tv_sec;
|
||||
mcs = ((ull)tv.tv_sec) * 1000000 + (ull)tv.tv_usec;
|
||||
average_wait_time = 0;
|
||||
}
|
||||
|
||||
// сохраняем последнюю отметку времени
|
||||
last_time = mcs;
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
max_wait_test();
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
int i = 0;
|
||||
|
||||
for (i = 0; i < 100; i++)
|
||||
if (i%3 == 0 && i%5 == 0)
|
||||
printf("FizzBuzz\n");
|
||||
else if (i%3 == 0)
|
||||
printf("Fizz\n");
|
||||
else if (i%5 == 0)
|
||||
printf("Buzz\n");
|
||||
else
|
||||
printf("%d\n", i);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
#include <stdlib.h>
|
||||
#include <malloc.h>
|
||||
|
||||
#define MALLOC(x,y) { y=malloc(x); if (!y) abort(); }
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
void * p = NULL;
|
||||
MALLOC(3,p);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
int k, o, a, l, v, d;
|
||||
int left1, left2, right;
|
||||
|
||||
for(k=0; k<10; k++)
|
||||
for(o=0; o<10; o++)
|
||||
for(a=0; a<10; a++)
|
||||
for(l=0; l<10; l++)
|
||||
for(v=0; v<10; v++)
|
||||
for(d=0; d<10; d++) {
|
||||
left1=left2=right=0;
|
||||
left1 *= 10; left1 += k;
|
||||
left1 *= 10; left1 += o;
|
||||
left1 *= 10; left1 += k;
|
||||
left1 *= 10; left1 += a;
|
||||
left2 *= 10; left2 += k;
|
||||
left2 *= 10; left2 += o;
|
||||
left2 *= 10; left2 += l;
|
||||
left2 *= 10; left2 += a;
|
||||
right*=10; right+=v;
|
||||
right*=10; right+=o;
|
||||
right*=10; right+=d;
|
||||
right*=10; right+=a;
|
||||
if(k==o || k==a || k==l || k==v || k==d ||
|
||||
o==a || o==l || o==v || o==d || a==l || a==v ||
|
||||
a==d || l==v || l==d || v==d)
|
||||
continue;
|
||||
if(left1 + left2 == right) {
|
||||
printf("%d%d%d%d+%d%d%d%d=%d%d%d%d\n",k,o,k,a,k,o,l,a,v,o,d,a);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
//~ const char * eq = "КОЗА+КОЗА=СТАДО";
|
||||
//~ int len = strlen(eq);
|
||||
//~ int i = 0;
|
||||
//~ char A='А';
|
||||
//~ for(i=0; i<len; i++)
|
||||
//~ switch(eq[i]) {
|
||||
//~ case '+' : printf("%c", eq[i]); break;
|
||||
//~ case '=' : printf("%c", eq[i]); break;
|
||||
//~ default: printf("%d", (int)eq[i]-(int)A); break;
|
||||
//~ };
|
||||
int k, o, z, a, s, t, d;
|
||||
int left, right;
|
||||
|
||||
for(k=1; k<10; k++)
|
||||
for(o=0; o<10; o++)
|
||||
for(z=0; z<10; z++)
|
||||
for(a=0; a<10; a++)
|
||||
for(s=1; s<10; s++)
|
||||
for(t=0; t<10; t++)
|
||||
for(d=0; d<10; d++) {
|
||||
left=right=0;
|
||||
left*=10; left+=k;
|
||||
left*=10; left+=o;
|
||||
left*=10; left+=z;
|
||||
left*=10; left+=a;
|
||||
left *= 2;
|
||||
right*=10; right+=s;
|
||||
right*=10; right+=t;
|
||||
right*=10; right+=a;
|
||||
right*=10; right+=d;
|
||||
right*=10; right+=o;
|
||||
//~ printf("left=%d right=%d", left, right);
|
||||
if(k==o || k==z || k==a || k==s || k==t || k==d ||
|
||||
o==z || o==a || o==s || o==t || o==d ||
|
||||
z==a || z==s || z==t || z==d ||
|
||||
a==s || a==t || a==d ||
|
||||
s==t || s==d ||
|
||||
t==d)
|
||||
continue;
|
||||
if(left == right) {
|
||||
printf("%d%d%d%d+%d%d%d%d=%d%d%d%d%d\n",k,o,z,a,k,o,z,a,s,t,a,d,o);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
int m, a, g, n, i, j, t, l, e, y;
|
||||
int left1, left2, right;
|
||||
|
||||
for(m=1; m<10; m++)
|
||||
for(a=0; a<10; a++)
|
||||
for(g=0; g<10; g++)
|
||||
for(n=0; n<10; n++)
|
||||
for(i=0; i<10; i++)
|
||||
for(j=0; j<10; j++)
|
||||
for(t=1; t<10; t++)
|
||||
for(l=0; l<10; l++)
|
||||
for(e=0; e<10; e++)
|
||||
for(y=0; y<10; y++) {
|
||||
left1=left2=right=0;
|
||||
left1 *= 10; left1 += m;
|
||||
left1 *= 10; left1 += a;
|
||||
left1 *= 10; left1 += g;
|
||||
left1 *= 10; left1 += n;
|
||||
left1 *= 10; left1 += i;
|
||||
left1 *= 10; left1 += j;
|
||||
left2 *= 10; left2 += t;
|
||||
left2 *= 10; left2 += a;
|
||||
left2 *= 10; left2 += n;
|
||||
left2 *= 10; left2 += t;
|
||||
left2 *= 10; left2 += a;
|
||||
left2 *= 10; left2 += l;
|
||||
right*=10; right+=m;
|
||||
right*=10; right+=e;
|
||||
right*=10; right+=t;
|
||||
right*=10; right+=a;
|
||||
right*=10; right+=l;
|
||||
right*=10; right+=l;
|
||||
right*=10; right+=y;
|
||||
if(m==a||m==g||m==n||m==i||m==j||m==t||m==l||m==e||m==y||
|
||||
a==g||a==n||a==i||a==j||a==t||a==l||a==e||a==y||
|
||||
g==n||g==i||g==j||g==t||g==l||g==e||g==y||
|
||||
n==i||n==j||n==t||n==l||n==e||n==y||
|
||||
i==j||i==t||i==l||i==e||i==y||
|
||||
j==t||j==l||j==e||j==y||
|
||||
t==l||t==e||t==y||
|
||||
l==e||l==y||
|
||||
e==y)
|
||||
continue;
|
||||
if(left1 + left2 == right) {
|
||||
printf("%d%d%d%d%d%d+%d%d%d%d%d%d=%d%d%d%d%d%d%d\n",m,a,g,n,i,j,t,a,n,t,a,l,m,e,t,a,l,l,y);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
|
||||
void
|
||||
termination_handler (int signum) {
|
||||
printf ("Performing kill task...\n");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
signal(SIGINT, termination_handler);
|
||||
|
||||
while(1==1);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
#ifndef INITIAL_LIMIT
|
||||
# define INITIAL_LIMIT 1025
|
||||
#endif
|
||||
char buf[2*INITIAL_LIMIT];
|
||||
|
||||
write_to_file(int id) {
|
||||
|
||||
char link[64];
|
||||
char * links = "/proc/self/fd/";
|
||||
sprintf(link, "%s", links);
|
||||
sprintf(link+strlen(links), "%d", id);
|
||||
//printf("link=%s\n", link);
|
||||
readlink(link, buf, INITIAL_LIMIT);
|
||||
//printf("buf=%s\n", buf);
|
||||
close(id);
|
||||
id = open(buf, O_WRONLY);
|
||||
write(id, "Hello world!\n", 13);
|
||||
close(id);
|
||||
}
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
int id = open("tmp.txt", O_RDONLY);
|
||||
|
||||
write_to_file(id);
|
||||
|
||||
return (0);
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
void syserr( const char *msg ) {
|
||||
perror(msg);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
main()
|
||||
{
|
||||
int rfd, wfd;
|
||||
char buff[64096];
|
||||
int nb;
|
||||
int ed;
|
||||
|
||||
remove("duck");
|
||||
|
||||
if( mkfifo( "duck", 0666 ) == -1 ) {
|
||||
syserr( "mkfifo" );
|
||||
}
|
||||
|
||||
switch( fork() ) {
|
||||
case -1: syserr("fork" ); break;
|
||||
case 0: // child
|
||||
printf( "Child awakes\n" );
|
||||
if( (rfd = open( "duck", O_RDWR )) == -1 ) {
|
||||
syserr( "open for reading" );
|
||||
}
|
||||
printf("Child: open completes\n");
|
||||
|
||||
for( ; ; ) {
|
||||
if( (nb = read( rfd, buff, 200 )) == -1 ) {
|
||||
syserr( "read" );
|
||||
}
|
||||
if( nb == 0 ) {
|
||||
printf("No more data\n");
|
||||
printf("child terminates 0\n");
|
||||
exit( 0 );
|
||||
}
|
||||
buff[nb] = '\0';
|
||||
printf("nb = %d Buff = |%s|\n", nb, buff);
|
||||
}
|
||||
break;
|
||||
default: // parent
|
||||
printf( "Parent awake\n" );
|
||||
if( (wfd = open( "duck", O_RDWR )) == -1 ) {
|
||||
syserr( "open for writing" );
|
||||
}
|
||||
printf("Parent opened pipe to write\n");
|
||||
|
||||
for( ed = 0; ed < 4; ed++ ) {
|
||||
sprintf( buff, "duckie %d", ed + 1 );
|
||||
if(write( wfd, buff, strlen(buff)) != strlen(buff)) {
|
||||
syserr( "write" );
|
||||
}
|
||||
}
|
||||
printf("parent terminates\n");
|
||||
close(wfd);
|
||||
remove("duck");
|
||||
sleep(1);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
/* Reading some text from the pipe. */
|
||||
void
|
||||
read_from_pipe (int file)
|
||||
{
|
||||
FILE *stream;
|
||||
int c;
|
||||
stream = fdopen (file, "r");
|
||||
while ( (c=fgetc(stream)) != EOF)
|
||||
putchar(c);
|
||||
//while(1==1) printf("%d\n",fgetc(stream));
|
||||
fclose (stream);
|
||||
}
|
||||
/* Writing some text to the pipe. */
|
||||
void
|
||||
write_to_pipe (int file)
|
||||
{
|
||||
FILE *stream;
|
||||
stream = fdopen (file, "w");
|
||||
fprintf (stream, "hello, world!\n");
|
||||
fprintf (stream, "goodbye, world!\n");
|
||||
fclose (stream);
|
||||
}
|
||||
int
|
||||
main (void)
|
||||
{
|
||||
pid_t pid;
|
||||
int mypipe[2];
|
||||
/* Creating unnamed pipe. */
|
||||
if (pipe (mypipe))
|
||||
{
|
||||
fprintf(stderr, "Pipe failed.\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
/* Creating child process because we need 2 processes to work with the pipe. */
|
||||
pid = fork ();
|
||||
if (pid == (pid_t) 0)
|
||||
{
|
||||
/* Child process opens the pipe for reading. */
|
||||
printf("child process for reading started\n");
|
||||
read_from_pipe (mypipe[0]);
|
||||
// write_to_pipe (mypipe[1]);
|
||||
close(mypipe[1]);
|
||||
printf("child process ended\n");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
else if (pid < (pid_t) 0)
|
||||
{
|
||||
/* If fork() failed. */
|
||||
fprintf(stderr,"Fork failed.\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Main (parent) process writes some data to the pipe. */
|
||||
printf("parent process for writing started\n");
|
||||
write_to_pipe (mypipe[1]);
|
||||
// read_from_pipe (mypipe[0]);
|
||||
printf("parent process ended\n");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
int i;
|
||||
for(i=0; i<10; i++) {
|
||||
fork();
|
||||
printf("Hello, world!\n");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
char string[] = "hello world";
|
||||
main()
|
||||
{
|
||||
int count,i;
|
||||
int to_par[2],to_chil[2]; /* для каналов родителя и
|
||||
потомка */
|
||||
char buf[256];
|
||||
pipe(to_par);
|
||||
pipe(to_chil);
|
||||
if (fork() == 0)
|
||||
{
|
||||
/* выполнение порожденного процесса */
|
||||
close(0); /* закрытие прежнего стандартного ввода */
|
||||
dup(to_chil[0]); /* дублирование дескриптора чтения
|
||||
из канала в позицию стандартного
|
||||
ввода */
|
||||
close(1); /* закрытие прежнего стандартного вывода */
|
||||
dup(to_par[0]); /* дублирование дескриптора записи
|
||||
в канал в позицию стандартного
|
||||
вывода */
|
||||
close(to_par[1]); /* закрытие ненужных дескрипторов
|
||||
close(to_chil[0]); канала */
|
||||
close(to_par[0]);
|
||||
close(to_chil[1]);
|
||||
for (;;)
|
||||
{
|
||||
if ((count = read(0,buf,sizeof(buf))) == 0)
|
||||
exit(0);
|
||||
write(1,buf,count);
|
||||
}
|
||||
}
|
||||
/* выполнение родительского процесса */
|
||||
close(1); /* перенастройка стандартного ввода-вывода */
|
||||
dup(to_chil[1]);
|
||||
close(0);
|
||||
dup(to_par[0]);
|
||||
close(to_chil[1]);
|
||||
close(to_par[0]);
|
||||
close(to_chil[0]);
|
||||
close(to_par[1]);
|
||||
for (i = 0; i < 15; i++)
|
||||
{
|
||||
write(1,string,strlen(string));
|
||||
read(0,buf,sizeof(buf));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
|
||||
void
|
||||
termination_handler (int signum) {
|
||||
printf ("Performing kill task...\n");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
signal(SIGINT, termination_handler);
|
||||
|
||||
while(1==1);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
#ifndef INITIAL_LIMIT
|
||||
# define INITIAL_LIMIT 1025
|
||||
#endif
|
||||
char buf[2*INITIAL_LIMIT];
|
||||
|
||||
write_to_file(int id) {
|
||||
|
||||
char link[64];
|
||||
char * links = "/proc/self/fd/";
|
||||
sprintf(link, "%s", links);
|
||||
sprintf(link+strlen(links), "%d", id);
|
||||
//printf("link=%s\n", link);
|
||||
readlink(link, buf, INITIAL_LIMIT);
|
||||
//printf("buf=%s\n", buf);
|
||||
close(id);
|
||||
id = open(buf, O_WRONLY);
|
||||
write(id, "Hello world!\n", 13);
|
||||
close(id);
|
||||
}
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
int id = open("tmp.txt", O_RDONLY);
|
||||
|
||||
write_to_file(id);
|
||||
|
||||
return (0);
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
void syserr( const char *msg ) {
|
||||
perror(msg);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
main()
|
||||
{
|
||||
int rfd, wfd;
|
||||
char buff[64096];
|
||||
int nb;
|
||||
int ed;
|
||||
|
||||
remove("duck");
|
||||
|
||||
if( mkfifo( "duck", 0666 ) == -1 ) {
|
||||
syserr( "mkfifo" );
|
||||
}
|
||||
|
||||
switch( fork() ) {
|
||||
case -1: syserr("fork" ); break;
|
||||
case 0: // child
|
||||
printf( "Child awakes\n" );
|
||||
if( (rfd = open( "duck", O_RDWR )) == -1 ) {
|
||||
syserr( "open for reading" );
|
||||
}
|
||||
printf("Child: open completes\n");
|
||||
|
||||
for( ; ; ) {
|
||||
if( (nb = read( rfd, buff, 200 )) == -1 ) {
|
||||
syserr( "read" );
|
||||
}
|
||||
if( nb == 0 ) {
|
||||
printf("No more data\n");
|
||||
printf("child terminates 0\n");
|
||||
exit( 0 );
|
||||
}
|
||||
buff[nb] = '\0';
|
||||
printf("nb = %d Buff = |%s|\n", nb, buff);
|
||||
}
|
||||
break;
|
||||
default: // parent
|
||||
printf( "Parent awake\n" );
|
||||
if( (wfd = open( "duck", O_RDWR )) == -1 ) {
|
||||
syserr( "open for writing" );
|
||||
}
|
||||
printf("Parent opened pipe to write\n");
|
||||
|
||||
for( ed = 0; ed < 4; ed++ ) {
|
||||
sprintf( buff, "duckie %d", ed + 1 );
|
||||
if(write( wfd, buff, strlen(buff)) != strlen(buff)) {
|
||||
syserr( "write" );
|
||||
}
|
||||
}
|
||||
printf("parent terminates\n");
|
||||
close(wfd);
|
||||
remove("duck");
|
||||
sleep(1);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
/* Reading some text from the pipe. */
|
||||
void
|
||||
read_from_pipe (int file)
|
||||
{
|
||||
FILE *stream;
|
||||
int c;
|
||||
stream = fdopen (file, "r");
|
||||
while ( (c=fgetc(stream)) != EOF)
|
||||
putchar(c);
|
||||
//while(1==1) printf("%d\n",fgetc(stream));
|
||||
fclose (stream);
|
||||
}
|
||||
/* Writing some text to the pipe. */
|
||||
void
|
||||
write_to_pipe (int file)
|
||||
{
|
||||
FILE *stream;
|
||||
stream = fdopen (file, "w");
|
||||
fprintf (stream, "hello, world!\n");
|
||||
fprintf (stream, "goodbye, world!\n");
|
||||
fclose (stream);
|
||||
}
|
||||
int
|
||||
main (void)
|
||||
{
|
||||
pid_t pid;
|
||||
int mypipe[2];
|
||||
/* Creating unnamed pipe. */
|
||||
if (pipe (mypipe))
|
||||
{
|
||||
fprintf(stderr, "Pipe failed.\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
/* Creating child process because we need 2 processes to work with the pipe. */
|
||||
pid = fork ();
|
||||
if (pid == (pid_t) 0)
|
||||
{
|
||||
/* Child process opens the pipe for reading. */
|
||||
printf("child process for reading started\n");
|
||||
read_from_pipe (mypipe[0]);
|
||||
// write_to_pipe (mypipe[1]);
|
||||
close(mypipe[1]);
|
||||
printf("child process ended\n");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
else if (pid < (pid_t) 0)
|
||||
{
|
||||
/* If fork() failed. */
|
||||
fprintf(stderr,"Fork failed.\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Main (parent) process writes some data to the pipe. */
|
||||
printf("parent process for writing started\n");
|
||||
write_to_pipe (mypipe[1]);
|
||||
// read_from_pipe (mypipe[0]);
|
||||
printf("parent process ended\n");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
1.
|
||||
(a) SIGINT signal sends to the main process
|
||||
(b) Example of SIGINT signal handler in the attachment: 1.c
|
||||
|
||||
2. Signals, shared memory, semaphors, mutexes, critical sections, events, named(streams) and unnamed pipes, sockets, local variables.
|
||||
|
||||
3. some_file will contain data(standard input stream) transfered through the unnamed pipe by simbol '|' to the 'echo' command.
|
||||
In that specific case some_file will contain no data.
|
||||
|
||||
4. Unnamed pipe is a set of processes chained by their standard streams.
|
||||
Named pipe is a method of inter-process communication which has name in the file system tree.
|
||||
|
||||
In shell:
|
||||
|
||||
$ mkfifo my_pipe
|
||||
or
|
||||
$ mknod my_pipe p
|
||||
will create a fifo pipe
|
||||
For example we can use it for compress some data.
|
||||
First process:
|
||||
$ gzip -9 -c < my_pipe > out.gz
|
||||
Second:
|
||||
$ cat Tsoj.txt > my_pipe
|
||||
and removing pipe:
|
||||
$ rm my_pipe
|
||||
or we can use '|' charecter for unnamed pipes (tubes/conveyors).
|
||||
|
||||
In C:
|
||||
|
||||
Function pipe(int id[2]) declared in unistd.h will create unnamed pipe,
|
||||
example of using it: 4unpipe.c is in the attachment.
|
||||
Function mkfifo (const char *filename, mode_t mode) declared in 'sys/stat.h'
|
||||
may create named pipe. Example: 4npipe.c is in the attachment.
|
||||
|
||||
If the receiving end of a pipe dies while the sending end still wants to write to the pipe
|
||||
sending end will die too !
|
||||
|
||||
5. (a) TCP server: socket, bind, listen, accept;
|
||||
(b) TCP client: socket, connect.
|
||||
|
||||
6. The program prints "Hello world!\n" of maximum child process number in UNIX times.
|
||||
10240 times on my Linux system. And then the program exits with bad status.
|
||||
|
||||
7. In run time we can use 'lsof' or 'fuser' command to find out is it opening any file or not.
|
||||
'ldd' use to find out which libraries it uses when not running executable file.
|
||||
finally $hex some.out|less, then press '/', input file name and search for the binary code.
|
||||
|
||||
8. Something like this:
|
||||
telnet mail.server.ua 25
|
||||
helo 95.83.108.87
|
||||
mail from: mecareful@server.ua
|
||||
rcpt to: somebody@somewhere.com
|
||||
Subject: Test letter
|
||||
Please don't reply to this letter.
|
||||
quit
|
||||
|
||||
9. Hard link is a directory reference, or pointer, to a file on a storage volume.
|
||||
$ ln some_file hard_link
|
||||
creates a hard link hard_link with the same node as a some_file.
|
||||
Example 9.sh in the attachment shows which three files are hardlinked to each other.
|
||||
|
||||
10. I use /proc/self/fd, example in the attachment: 10.c.
|
|
@ -0,0 +1,10 @@
|
|||
#include <stdio.h>
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
FILE * stream;
|
||||
int c;
|
||||
stream = fopen("myfifo","r");
|
||||
while ((c=fgetc(stream)) != EOF)
|
||||
printf("%d\n",c);
|
||||
return (0);
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
#!/bin/sh
|
||||
|
||||
#Создаем объектный файл
|
||||
gcc -Wall -g -c -o libhello-static.o libhello.c && \
|
||||
#Создаем статическую библиотеку
|
||||
ar rcs libhello-static.a libhello-static.o && \
|
||||
#Если обладаете правами суперпользователя, то можно выполнить
|
||||
#cp libhello-static.a /usr/local/lib/
|
||||
#Иначе оставляем статическую библиотеку в текущей директории
|
||||
#Создаем объектный файл
|
||||
gcc -Wall -g -c demo_use.c -o demo_use.o && \
|
||||
#Создаем исполняемый файл
|
||||
#-L. - этот параметр указывает компилятору, что библиотеку следует искать в текущей директории.
|
||||
#-lhello-static - этот параметр указывает компилятору, что библиотека помещается в файле
|
||||
#libhello-static.расширение (.a, .o, .so).
|
||||
gcc -g -o demo_use_static demo_use.o -L. -lhello-static && \
|
||||
#Выполнение исполняемого файла
|
||||
./demo_use_static
|
|
@ -0,0 +1,6 @@
|
|||
#include "libhello.h"
|
||||
|
||||
int main() {
|
||||
hello();
|
||||
return 0;
|
||||
}
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,6 @@
|
|||
#include <stdio.h>
|
||||
#include "libhello.h"
|
||||
|
||||
void hello(void) {
|
||||
printf("Hello, library world.\n");
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
void hello(void);
|
|
@ -0,0 +1 @@
|
|||
build.sh
|
|
@ -0,0 +1,9 @@
|
|||
#!/bin/sh
|
||||
|
||||
rm -f test test.o
|
||||
gcc -static -o test main.c
|
||||
#gcc -c -static test.o main.c && \
|
||||
#ld -static -o test test.o && \
|
||||
#rm test.o
|
||||
|
||||
./test
|
|
@ -0,0 +1,23 @@
|
|||
#include <stdio.h>
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define MaxLen 1024
|
||||
char STR1[1024], STR2[1024];
|
||||
int strcomp(const char * str1, const char * str2)
|
||||
{
|
||||
char * p1 = STR1, * p2 = STR2;
|
||||
while(*p1++=toupper(*str1++));
|
||||
while(*p2++=toupper(*str2++));
|
||||
return strcmp(STR1,STR2);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
printf("%d\n", strcomp("Hello\0","heLLo\0"));
|
||||
printf("%d\n", strcomp("aello\0","BeLLo\0"));
|
||||
printf("%d\n", strcomp("bello\0","AeLLo\0"));
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
int sz = 1524*1024*1024;
|
||||
printf("%d",sz);
|
||||
char * m = (char*)malloc(sz);
|
||||
if(m==NULL)
|
||||
{
|
||||
printf("malloc failed\n");
|
||||
exit(-1);
|
||||
}
|
||||
int i;
|
||||
for(i=0; i<sz; i++) m[i]=0;
|
||||
sleep(5);
|
||||
// free(m);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
//#include <unistd.h>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
int sz = 1024*1024*1024;
|
||||
cout<<sz;
|
||||
char * m = new char[sz];
|
||||
if(m==NULL)
|
||||
{
|
||||
cout<<"new failed\n";
|
||||
exit(-1);
|
||||
}
|
||||
for(int i=0; i<sz; i++) m[i]=0;
|
||||
sleep(5);
|
||||
// delete m;
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
printf("Hello, world!\n");
|
||||
getc(stdin);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
|
@ -0,0 +1,152 @@
|
|||
#include <stdlib.h>
|
||||
|
||||
|
||||
/* подключаем библиотеку GLUT */
|
||||
|
||||
#include <GL/glut.h>
|
||||
|
||||
|
||||
|
||||
/* начальная ширина и высота окна */
|
||||
|
||||
GLint Width = 512, Height = 512;
|
||||
|
||||
|
||||
|
||||
/* размер куба */
|
||||
|
||||
const int CubeSize = 200;
|
||||
|
||||
|
||||
|
||||
/* эта функция управляет всем выводом на экран */
|
||||
|
||||
void Display(void)
|
||||
|
||||
{
|
||||
|
||||
int left, right, top, bottom;
|
||||
|
||||
|
||||
|
||||
left = (Width - CubeSize) / 2;
|
||||
|
||||
right = left + CubeSize;
|
||||
|
||||
bottom = (Height - CubeSize) / 2;
|
||||
|
||||
top = bottom + CubeSize;
|
||||
|
||||
|
||||
|
||||
glClearColor(0, 0, 0, 1);
|
||||
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
|
||||
|
||||
|
||||
glColor3ub(255,0,0);
|
||||
|
||||
glBegin(GL_QUADS);
|
||||
|
||||
glVertex2f(left,bottom);
|
||||
|
||||
glVertex2f(left,top);
|
||||
|
||||
glVertex2f(right,top);
|
||||
|
||||
glVertex2f(right,bottom);
|
||||
|
||||
glEnd();
|
||||
|
||||
|
||||
|
||||
glFinish();
|
||||
|
||||
}
|
||||
|
||||
/* Функция вызывается при изменении размеров окна */
|
||||
|
||||
void Reshape(GLint w, GLint h)
|
||||
|
||||
{
|
||||
|
||||
Width = w;
|
||||
|
||||
Height = h;
|
||||
|
||||
|
||||
|
||||
/* устанавливаем размеры области отображения */
|
||||
|
||||
glViewport(0, 0, w, h);
|
||||
|
||||
|
||||
|
||||
/* ортографическая проекция */
|
||||
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
|
||||
glLoadIdentity();
|
||||
|
||||
glOrtho(0, w, 0, h, -1.0, 1.0);
|
||||
|
||||
|
||||
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
|
||||
glLoadIdentity();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/* Функция обрабатывает сообщения от клавиатуры */
|
||||
|
||||
void
|
||||
|
||||
Keyboard( unsigned char key, int x, int y )
|
||||
|
||||
{
|
||||
|
||||
#define ESCAPE '\033'
|
||||
|
||||
|
||||
|
||||
if( key == ESCAPE )
|
||||
|
||||
exit(0);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* Главный цикл приложения */
|
||||
|
||||
main(int argc, char *argv[])
|
||||
|
||||
{
|
||||
|
||||
glutInit(&argc, argv);
|
||||
|
||||
glutInitDisplayMode(GLUT_RGB);
|
||||
|
||||
glutInitWindowSize(Width, Height);
|
||||
|
||||
glutCreateWindow("Red square example");
|
||||
|
||||
|
||||
|
||||
glutDisplayFunc(Display);
|
||||
|
||||
glutReshapeFunc(Reshape);
|
||||
|
||||
glutKeyboardFunc(Keyboard);
|
||||
|
||||
|
||||
|
||||
glutMainLoop();
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
|
||||
printf("%ld", sizeof(off_t));
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <signal.h>
|
||||
void term_handler(int i)
|
||||
{ printf ("Terminating\n");
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
int main(int argc, char ** argv) {
|
||||
struct sigaction sa;
|
||||
sigset_t newset;
|
||||
sigemptyset(&newset);
|
||||
sigaddset(&newset, SIGHUP);
|
||||
sigprocmask(SIG_BLOCK, &newset, 0);
|
||||
sa.sa_handler = term_handler;
|
||||
sigaction(SIGTERM, &sa, 0);
|
||||
printf("My pid is %i\n", getpid());
|
||||
printf("Waiting...\n");
|
||||
while(1) sleep(1);
|
||||
return EXIT_FAILURE;
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
#include <iostream>
|
||||
#include <stdlib.h>
|
||||
#include <math.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
const int NEXPER = 10000;
|
||||
|
||||
int main(void) {
|
||||
srand(time(0));
|
||||
|
||||
int M = 0, N = 0;
|
||||
// Повторяем эксперимент NEXPER раз
|
||||
for (N = 0; N < NEXPER; N++) {
|
||||
// за одной из 3-х досок автомобиль
|
||||
int WonDesk = rand()%3 + 1; // 1,2 или 3
|
||||
// мы указываем на доску №1,
|
||||
// после чего ведущий открывает 1-ну из досок
|
||||
int OdnaIsDosok = rand()%2 + 2; // 2 или 3
|
||||
if (OdnaIsDosok == WonDesk) { // если за ней автомобиль, то он должен однозначно открыть не эту
|
||||
OdnaIsDosok = OdnaIsDosok==2 ? 3 : 2;
|
||||
}
|
||||
// мы изменяем выбор и подсчитываем вероятность
|
||||
if (WonDesk != 1) M++; // если автомобиль не за 1-ой доской, то при изменении выбора едем домой на 4-х =)
|
||||
}
|
||||
|
||||
cout << "p = " << (double(M)/double(N)) << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
using namespace std;ывав
|
||||
typedef unsigned long long ll;
|
||||
ll f(ll m, ll n) {
|
||||
if(m==0) return n+1;
|
||||
if(n==0) return f(m-1,1);
|
||||
return f(m-1,f(m,n-1));
|
||||
}
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
for(int i=0;i<30;i++) cout << "akk("<<3<<";"<<i<<") = "<<f(3,i)<<endl;
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
/* STL */
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
/* STD */
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <math.h>
|
||||
using namespace std;
|
||||
|
||||
void showlist (const char *str, const list<int> &L) {
|
||||
list<int>::const_iterator i;
|
||||
cout << str << endl << " ";
|
||||
for (i=L.begin(); i != L.end(); ++i)
|
||||
cout << *i << " ";
|
||||
cout << endl;
|
||||
}
|
||||
|
||||
int main (int argc, char *argv[]) {
|
||||
list<int> L;
|
||||
int x;
|
||||
cout << "Enter positive integers, followed by 0:\n";
|
||||
while (cin >> x, x != 0)
|
||||
L.push_back(x);
|
||||
showlist("Initial list:", L);
|
||||
L.push_front(123);
|
||||
showlist("After inserting 123 at the beginning:", L);
|
||||
list<int>::iterator i = L.begin();
|
||||
L.insert(++i, 456);
|
||||
showlist("After inserting 456 at the second position:", L);
|
||||
i = L.end();
|
||||
L.insert(--i, 999);
|
||||
showlist("After inserting 999 just before the end:", L);
|
||||
i = L.begin(); x = *i;
|
||||
L.pop_front();
|
||||
cout << "Deleted at the beginning: " << x << endl;
|
||||
showlist("After this deletion:", L);
|
||||
i = L.end(); x = *--i;
|
||||
L.pop_back();
|
||||
cout << "Deleted at the end: " << x << endl;
|
||||
showlist("After this deletion:", L);
|
||||
i = L.begin();
|
||||
x = *++i; cout << "To be deleted: " << x << endl;
|
||||
L.erase(i);
|
||||
showlist("After this deletion (of second element):", L);
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
/* STL */
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
/* STD */
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <math.h>
|
||||
using namespace std;
|
||||
|
||||
int main (int argc, char *argv[]) {
|
||||
vector<int> v;
|
||||
int x;
|
||||
cout << "Enter positive integers, followed by 0:\n";
|
||||
while (cin >> x, x !=0) v.push_back(x);
|
||||
sort(v.begin(), v.end());
|
||||
cout << "After sorting: \n";
|
||||
vector<int>::iterator i;
|
||||
for (i=v.begin(); i != v.end(); ++i)
|
||||
cout << *i << " ";
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
/* STL */
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
/* STD */
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <math.h>
|
||||
using namespace std;
|
||||
|
||||
int main (int argc, char *argv[]) {
|
||||
int a[10], x, n = 0, *p;
|
||||
cout << "Enter at most 10 positive integers, followed by 0:\n";
|
||||
while (cin >> x, x != 0 && n < 10) a[n++] = x;
|
||||
sort(a, a+n);
|
||||
cout << "After sorting: \n";
|
||||
for (p=a; p != a+n; p++) cout << *p << " ";
|
||||
cout << endl;
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
/* STL */
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
/* STD */
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <math.h>
|
||||
using namespace std;
|
||||
|
||||
// 1.5. Алгоритм find Найти заданное значение в векторе
|
||||
|
||||
int main (int argc, char *argv[]) {
|
||||
vector<int> v;
|
||||
int x;
|
||||
cout << "Enter positive integers, followed by 0:\n";
|
||||
while (cin >> x, x != 0)
|
||||
v.push_back(x);
|
||||
|
||||
cout << "Value to be searched for: ";
|
||||
cin >> x;
|
||||
vector<int>::iterator i = find(v.begin(), v.end(), x);
|
||||
if (i == v.end()) cout << "Not found\n";
|
||||
else {
|
||||
cout << "Found";
|
||||
if (i == v.begin()) cout << " as the first element";
|
||||
else cout << " after " << *--i;
|
||||
}
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
/* STL */
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
/* STD */
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <math.h>
|
||||
using namespace std;
|
||||
|
||||
int main (int argc, char *argv[]) {
|
||||
int a[4] = {10, 20, 30, 40};
|
||||
vector<int> v(a, a+4);
|
||||
list<int> L(4); // Список из 4 элементов
|
||||
copy(v.begin(), v.end(), inserter(L, L.begin()));//L.begin());
|
||||
list<int>::iterator i;
|
||||
for (i=L.begin(); i != L.end(); ++i)
|
||||
cout << *i << " ";
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
/* STL */
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
/* STD */
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <math.h>
|
||||
using namespace std;
|
||||
|
||||
int main (int argc, char *argv[]) {
|
||||
int a[4] = {10, 20, 30, 40};
|
||||
vector<int> v(a, a+4);
|
||||
list<int> L(4); // Список из 4 элементов
|
||||
copy(v.begin(), v.end(), inserter(L, ++(++(L.begin()))));//L.begin());
|
||||
list<int>::iterator i;
|
||||
for (i=L.begin(); i != L.end(); ++i)
|
||||
cout << *i << " ";
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
/* STL */
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
/* STD */
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <math.h>
|
||||
using namespace std;
|
||||
|
||||
/* Объединение вектора и массива в список
|
||||
*/
|
||||
|
||||
int main (int argc, char *argv[]) {
|
||||
vector<int> a(5);
|
||||
a[0] = 2; a[1] = 3; a[2] = 8;
|
||||
a[3] = 20; a[4] = 25;
|
||||
int b[6] = {7, 9, 23, 28, 30, 33};
|
||||
list<int> c; // Список с начала пуст
|
||||
merge(a.begin(), a.end(), b, b+6, inserter(c, c.begin()));
|
||||
list<int>::iterator i;
|
||||
for (i=c.begin(); i != c.end(); ++i)
|
||||
cout << *i << " ";
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
/* STL */
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
/* STD */
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <math.h>
|
||||
using namespace std;
|
||||
|
||||
// Объединяем записи, используя имена в качестве ключей
|
||||
|
||||
struct entry {
|
||||
long nr;
|
||||
char name[30];
|
||||
bool operator<(const entry &b) const {
|
||||
return strcmp(name, b.name) < 0;
|
||||
}
|
||||
};
|
||||
|
||||
int main (int argc, char *argv[]) {
|
||||
entry a[3] = {{10, "Betty"},
|
||||
{11, "James"},
|
||||
{80, "Jim"}},
|
||||
b[2] = {{16, "Fred"},
|
||||
{20, "William"}},
|
||||
c[5], *p;
|
||||
merge(a, a+3, b, b+2, c);
|
||||
for (p=c; p != c+5; p++)
|
||||
cout << p->nr << " " << p->name << endl;
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
#!/bin/bash
|
||||
|
||||
for i in 0 1 2 3 4 5 6 7 8 9; do
|
||||
for j in 0 1 2 3 4 5 6 7 8 9; do
|
||||
dirname=$i$j
|
||||
mkdir $dirname
|
||||
cp main.cpp $dirname
|
||||
done
|
||||
done
|
|
@ -0,0 +1,64 @@
|
|||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
int razmer; //размер матрицы
|
||||
double **a, // матрица с коэфицентами
|
||||
*x, // х
|
||||
*b; // свободные члены
|
||||
/* Здесь переменной razmer необходимо присвоить размер матрицы */
|
||||
// создание динамических переменных
|
||||
b = new double[razmer];
|
||||
x = new double[razmer];
|
||||
a = new double*[razmer];
|
||||
for(int i=0; i < razmer; i++){
|
||||
a[i] = new double[razmer];
|
||||
}
|
||||
/* Здесь нам надо присвоить значения матрице а, и заполнить свободные члены b */
|
||||
|
||||
// начинаем решать)
|
||||
// частный случай, если размер матрицы == 1
|
||||
if(razmer == 1){
|
||||
if(a[0][0] != 0){
|
||||
cout << "x=" << b[0]/a[0][0] << endl;
|
||||
}else{
|
||||
cout << "Х любое" << endl;
|
||||
}
|
||||
sleep(5);//getch();
|
||||
exit(0);
|
||||
}
|
||||
// прямой проход
|
||||
// идем слево на право по коэфицентам х
|
||||
for(int k=0; k < razmer-1; k++){
|
||||
// вычитаем по строкам
|
||||
for(int m=k+1; m < razmer; m++){
|
||||
// если на диагонали элемент = 0, то поменяем местами строки
|
||||
if(a[m][m] == 0) exchange(a, razmer, m, get_n_no_empty(a, razmer, m));
|
||||
|
||||
double koeficent=a[m][k]/a[0][k];
|
||||
//вычисление новых коэфицентов уравнения
|
||||
b[m] = b[m] - b[0] * koeficent;
|
||||
for(int z=0; z < razmer; z++){
|
||||
a[m][z] = a[m][k] - a[0][k] * koeficent;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
// ищем решения
|
||||
for(int m=razmer-1; m >= 0; m--){
|
||||
double sum=0;
|
||||
// идем по строке спаво налево, считая сумму корень*коэфицент, до текущего корня
|
||||
for(int i=razmer-1; i > m; i--){
|
||||
sum += x[i] * a[m][i];
|
||||
}
|
||||
x[m] = (b[m] - sum)/a[m][m];
|
||||
}
|
||||
|
||||
// вывод решений
|
||||
cout << "###Решения:" << endl;
|
||||
for(int i=0; i < razmer; i++){
|
||||
cout << "x[" << i << "]=" << x[i] << endl;
|
||||
}
|
||||
pause();
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
#include <iostream>
|
||||
using namespace std;
|
||||
const int n=350;
|
||||
typedef double massive[2*n+1][2*n+1];
|
||||
double a_k[2*n+1];
|
||||
double b[2*n+1];
|
||||
double c[2*n+1];
|
||||
double right_part[2*n+1];
|
||||
double sys[2*n+1][2*n+1];
|
||||
void sys_solve()
|
||||
{
|
||||
int i,j,k;
|
||||
double sum=0.0;
|
||||
double f[2*n+1];
|
||||
massive b,c;
|
||||
|
||||
//Прямой ход
|
||||
for(i=0;i<2*n+1;i++) b[i][i]=1.0;
|
||||
for(j=0;j<2*n+1;j++)
|
||||
{
|
||||
for(i=j;i<2*n+1;i++)
|
||||
{
|
||||
sum=0.0;
|
||||
for(k=0;k<j;k++) sum=sum+c[i][k]*b[k][j];
|
||||
c[i][j]=sys[i][j]-sum;
|
||||
}
|
||||
for(i=j+1;i<2*n+1;i++)
|
||||
{
|
||||
sum=0.0;
|
||||
for(k=0;k<j;k++) sum=sum+c[j][k]*b[k][i];
|
||||
b[j][i]=(sys[j][i]-sum)/c[j][j];
|
||||
}
|
||||
}
|
||||
for(j=0;j<2*n+1;j++)
|
||||
{
|
||||
sum=0.0;
|
||||
for(k=0;k<j;k++) sum=sum+c[j][k]*f[k];
|
||||
f[j]=(right_part[j]-sum)/c[j][j];
|
||||
}
|
||||
//Обратный ход
|
||||
for(j=2*n;j>=0;j--)
|
||||
{
|
||||
sum=0.0;
|
||||
for(k=j+1;k<2*n+1;k++) sum=sum+b[j][k]*a_k[k];
|
||||
a_k[j]=f[j]-sum;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
sys_solve();
|
||||
cout<<"end"<<endl;char ch;cin>>ch;
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
#include <iostream>
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
std::cout<<"Hello, world!"<<std::endl;
|
||||
int a = 3.14;
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
#ifndef _KLMN_LU_SOLVE_
|
||||
#define _KLMN_LU_SOLVE_
|
||||
|
||||
#include <boost/numeric/ublas/triangular.hpp>
|
||||
#include <boost/numeric/ublas/blas.hpp>
|
||||
#include <boost/numeric/ublas/lu.hpp>
|
||||
|
||||
// boost: разворот вектора на месте (y[0]<->y[n], y[1]<->y[n-1],...)
|
||||
template <typename T>
|
||||
void inplace_turn(boost::numeric::ublas::vector<T>& v)
|
||||
{
|
||||
for(size_t i=0, max_i=v.size()/2, j=v.size()-1; i<max_i; i++,j--)
|
||||
{
|
||||
T tmp = v(i);
|
||||
v(i) = v(j);
|
||||
v(j) = tmp;
|
||||
}
|
||||
}
|
||||
|
||||
// boost: решение системы A*x = b методом LU-разложения за O(n) шагов
|
||||
// матрица A не сохраняется, решение в b (для оптимизации по скорости и памяти)
|
||||
// алгоритм требует дополнительную память при копировании A в L и U,
|
||||
// размер кт. равен памяти, выделяемой под матрицу A.
|
||||
template <typename T>
|
||||
void lu_solve (boost::numeric::ublas::matrix<T>& A, boost::numeric::ublas::vector<T>& b)
|
||||
{
|
||||
using namespace boost::numeric::ublas;
|
||||
|
||||
// получаем L и U на месте A
|
||||
lu_factorize(A);
|
||||
|
||||
// "вытаскиваем" L из A
|
||||
size_t N = A.size1();
|
||||
boost::numeric::ublas::triangular_matrix<T> L(N,N);
|
||||
for(size_t i=1; i<N; i++)
|
||||
for(size_t j=0; j<i; j++)
|
||||
L(i,j) = A(i,j);
|
||||
for(size_t i=0; i<N; i++)
|
||||
L(i,i) = 1;
|
||||
|
||||
// "вытаскиваем" U из A
|
||||
boost::numeric::ublas::triangular_matrix<T> U(N,N);
|
||||
for(size_t i=0; i<N; i++)
|
||||
for(size_t j=i; j<N; j++)
|
||||
U(N-1-i,N-1-j) = A(i,j);
|
||||
|
||||
// освобождаем память из-под A
|
||||
A.resize(0,0);
|
||||
|
||||
// решаем Ly=Pb
|
||||
inplace_solve(L,b,lower_tag());
|
||||
inplace_turn(b);
|
||||
L.resize(0,0);
|
||||
|
||||
// решаем Ux=y
|
||||
inplace_solve(U,b,lower_tag());
|
||||
inplace_turn(b);
|
||||
}
|
||||
|
||||
#endif // _KLMN_LU_SOLVE_
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
#include <boost/numeric/ublas/io.hpp>
|
||||
#include "lu_solve.hpp"
|
||||
|
||||
namespace bnu=boost::numeric::ublas;
|
||||
|
||||
void test1()
|
||||
{
|
||||
bnu::matrix<double> A(3,3);
|
||||
A(0,0) = 1; A(0,1) = 2; A(0,2) = 3;
|
||||
A(1,0) = 3; A(1,1) = 5; A(1,2) = 7;
|
||||
A(2,0) = 1; A(2,1) = 3; A(2,2) = 4;
|
||||
|
||||
std::cout<<"A="<<A<<std::endl;
|
||||
|
||||
bnu::vector<double> v(3);
|
||||
v(0) = 3; v(1) = 0; v(2) = 1;
|
||||
std::cout<<"b="<<v<<std::endl;
|
||||
|
||||
lu_solve(A,v);
|
||||
|
||||
std::cout<<"x="<<v<<std::endl;
|
||||
}
|
||||
|
||||
void test2(size_t N=1024)
|
||||
{
|
||||
bnu::matrix<double> A(N,N);
|
||||
for(size_t i=0; i<N; i++)
|
||||
A(i,i) = 1;
|
||||
|
||||
bnu::vector<double> v(N);
|
||||
for(size_t i=0; i<N; i++)
|
||||
v(i) = i/10.0;
|
||||
|
||||
lu_solve(A,v);
|
||||
|
||||
// std::cout<<"x="<<v<<std::endl;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout<<"start..."<<std::endl;
|
||||
// test1();
|
||||
test2(500);
|
||||
std::cout<<"stop"<<std::endl;
|
||||
return 0;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
int a[ 5 ];
|
||||
|
||||
void * Thread( void* pParams )
|
||||
{ int i, num = 0;
|
||||
|
||||
while ( 1 )
|
||||
{
|
||||
for ( i = 0; i < 5; i++ ) a[ i ] = num;
|
||||
num++;
|
||||
|
||||
//~ struct timespec ts;
|
||||
//~ ts.tv_sec = 0;
|
||||
//~ ts.tv_nsec = 10;
|
||||
//~ nanosleep(&ts,NULL);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
int main( void )
|
||||
{
|
||||
pthread_t tr;
|
||||
if(pthread_create(&tr,NULL,Thread,NULL) != 0)
|
||||
return EXIT_FAILURE;
|
||||
|
||||
|
||||
|
||||
// _beginthread( Thread, 0, NULL );
|
||||
|
||||
while( 1 )
|
||||
printf("%d %d %d %d %d\n",
|
||||
a[ 0 ], a[ 1 ], a[ 2 ],
|
||||
a[ 3 ], a[ 4 ] );
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
#include <stdio.h>
|
||||
|
||||
int i; main(){for(;i["]<i;++i){--i;}"];read('-'-'-',i+++"hell\
|
||||
o, world!\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);
|
|
@ -0,0 +1,82 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/sem.h>
|
||||
|
||||
|
||||
//~ HANDLE hEvent1, hEvent2;
|
||||
int key = 0x20; // Semaphore key
|
||||
|
||||
int a[ 5 ];
|
||||
|
||||
void Thread( void* pParams )
|
||||
{
|
||||
// Thread 2
|
||||
struct sembuf operation[1] ;
|
||||
|
||||
// open semaphore
|
||||
int mysemid = semget(key, 2, 0);
|
||||
|
||||
operation[0].sem_op = 1; // Release on the second resource
|
||||
operation[0].sem_num = 1;
|
||||
operation[0].sem_flg = SEM_UNDO;
|
||||
|
||||
//Release semaphore 2
|
||||
semop(mysemid, operation, 1);
|
||||
|
||||
int i, num = 0;
|
||||
|
||||
while ( 1==1 )
|
||||
{
|
||||
WaitForSingleObject( hEvent2, INFINITE );
|
||||
for ( i = 0; i < 5; i++ ) a[ i ] = num;
|
||||
SetEvent( hEvent1 );
|
||||
num++;
|
||||
}
|
||||
}
|
||||
|
||||
int main( void )
|
||||
{
|
||||
// Thread 1
|
||||
struct sembuf operation[2] ;
|
||||
|
||||
// Create 2 semaphores
|
||||
semid = semget(key, 2, 0666 | IPC_CREAT);
|
||||
|
||||
|
||||
operation[0].sem_op = 1; //Release first resource
|
||||
operation[0].sem_num = 0;
|
||||
operation[0].sem_flg = SEM_UNDO;
|
||||
|
||||
operation[0].sem_op = -1; // Wait on the second resource
|
||||
operation[0].sem_num = 1;
|
||||
operation[0].sem_flg = SEM_UNDO;
|
||||
|
||||
//Release semaphore 1 and wait on semaphore 2
|
||||
// note : thread is suspended until the semaphore 2 is released.
|
||||
semop(semid, operation, 2);
|
||||
|
||||
// thread is released
|
||||
// delete the semaphore
|
||||
semctl(semid, 0, IPC_RMID , 0)
|
||||
|
||||
hEvent1 = CreateEvent( NULL, FALSE, TRUE, NULL );
|
||||
hEvent2 = CreateEvent( NULL, FALSE, FALSE, NULL );
|
||||
|
||||
_beginthread( Thread, 0, NULL );
|
||||
|
||||
while( 1==1 )
|
||||
{
|
||||
WaitForSingleObject( hEvent1, INFINITE );
|
||||
printf( "%d %d %d %d %d\n",
|
||||
a[ 0 ], a[ 1 ], a[ 2 ],
|
||||
a[ 3 ], a[ 4 ] );
|
||||
SetEvent( hEvent2 );
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
//~ CRITICAL_SECTION cs;
|
||||
pthread_mutex_t mutex; // Mutex
|
||||
|
||||
int a[ 5 ];
|
||||
|
||||
void *Thread( void* pParams )
|
||||
{
|
||||
int i, num = 0;
|
||||
|
||||
while ( 1==1 )
|
||||
{
|
||||
//~ EnterCriticalSection( &cs );
|
||||
pthread_mutex_lock(&mutex);
|
||||
for ( i = 0; i < 5; i++ ) a[ i ] = num;
|
||||
//~ LeaveCriticalSection( &cs );
|
||||
pthread_mutex_unlock(&mutex);
|
||||
num++;
|
||||
}
|
||||
}
|
||||
|
||||
int main( void )
|
||||
|
||||
{
|
||||
//~ InitializeCriticalSection( &cs );
|
||||
pthread_mutex_init(&mutex,NULL);
|
||||
//~ _beginthread( Thread, 0, NULL );
|
||||
pthread_t tr;
|
||||
if(pthread_create(&tr,NULL,Thread,NULL) != 0)
|
||||
return EXIT_FAILURE;
|
||||
|
||||
while( 1==1 )
|
||||
{
|
||||
//~ EnterCriticalSection( &cs );
|
||||
pthread_mutex_lock(&mutex);
|
||||
printf( "%d %d %d %d %d\n",
|
||||
a[ 0 ], a[ 1 ], a[ 2 ],
|
||||
a[ 3 ], a[ 4 ] );
|
||||
//~ LeaveCriticalSection( &cs );
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
static void wait_thread(void)
|
||||
{
|
||||
time_t start_time = time(NULL);
|
||||
|
||||
while (time(NULL) == start_time)
|
||||
{
|
||||
/* do nothing except chew CPU slices for up to one second. */
|
||||
//usleep(1);
|
||||
//~ struct timespec
|
||||
//~ {
|
||||
//~ time_t tv_sec; /* секунды */
|
||||
//~ long tv_nsec; /* наносекунды */
|
||||
//~ };
|
||||
|
||||
//~ struct timespec ts;
|
||||
//~ ts.tv_sec = 0;
|
||||
//~ ts.tv_nsec = 10;
|
||||
//~ nanosleep(&ts,NULL);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
static void *thread_func(void *vptr_args)
|
||||
{
|
||||
int i;
|
||||
|
||||
for (i = 0; i < 10; i++)
|
||||
{
|
||||
fputs(" b\n", stderr);
|
||||
wait_thread();
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int i;
|
||||
pthread_t thread;
|
||||
|
||||
if (pthread_create(&thread, NULL, thread_func, NULL) != 0)
|
||||
{
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
for (i = 0; i < 10; i++)
|
||||
{
|
||||
puts("a");
|
||||
wait_thread();
|
||||
}
|
||||
|
||||
if (pthread_join(thread, NULL) != 0)
|
||||
{
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
#include <pthread.h>
|
||||
|
||||
class Thread
|
||||
{
|
||||
private:
|
||||
pthread_t thread;
|
||||
|
||||
Thread(const Thread& copy); // copy constructor denied
|
||||
static void *thread_func(void *d) { ((Thread *)d)->run(); return NULL; }
|
||||
|
||||
public:
|
||||
Thread() {}
|
||||
virtual ~Thread() {}
|
||||
|
||||
virtual void run() = 0;
|
||||
|
||||
int start() { return pthread_create(&thread, NULL,
|
||||
Thread::thread_func, (void*)this); }
|
||||
int wait () { return pthread_join (thread, NULL); }
|
||||
};
|
||||
|
||||
typedef std::auto_ptr<Thread> ThreadPtr;
|
||||
|
||||
int main(void)
|
||||
{
|
||||
class Thread_a:public Thread
|
||||
{
|
||||
public:
|
||||
void run()
|
||||
{
|
||||
for (int i=0; i<20; i++, sleep(1))
|
||||
std::cout << "a " << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
class Thread_b:public Thread
|
||||
{
|
||||
public:
|
||||
void run()
|
||||
{
|
||||
for(int i=0; i<20; i++, sleep(1))
|
||||
std::cout << " b" << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
ThreadPtr a( new Thread_a() );
|
||||
ThreadPtr b( new Thread_b() );
|
||||
|
||||
if (a->start() != 0 || b->start() != 0)
|
||||
return EXIT_FAILURE;
|
||||
|
||||
if (a->wait() != 0 || b->wait() != 0)
|
||||
return EXIT_FAILURE;
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
|
||||
[indentation]
|
||||
indent_width=4
|
||||
indent_type=1
|
||||
indent_hard_tab_width=8
|
||||
detect_indent=false
|
||||
indent_mode=2
|
||||
|
||||
[project]
|
||||
name=pthread_ex
|
||||
base_path=/home/kolan/Projects/cpp/multithreading/
|
||||
description=
|
||||
|
||||
[long line marker]
|
||||
long_line_behaviour=1
|
||||
long_line_column=72
|
||||
|
||||
[files]
|
||||
current_page=6
|
||||
FILE_NAME_0=472;C;0;16;1;1;0;/home/kolan/Projects/cpp/multithreading/asynch.c;0
|
||||
FILE_NAME_1=328;C;0;16;1;1;0;/home/kolan/Projects/cpp/multithreading/mutexes.c;0
|
||||
FILE_NAME_2=1354;C;0;16;1;1;0;/home/kolan/Projects/cpp/multithreading/semabinit.c;0
|
||||
FILE_NAME_3=642;C;0;16;1;1;0;/home/kolan/Projects/cpp/multithreading/sem08-1a.c;0
|
||||
FILE_NAME_4=2155;C;0;16;1;1;0;/home/kolan/Projects/cpp/multithreading/sem08-1b.c;0
|
||||
FILE_NAME_5=100;C;0;16;1;1;0;/home/kolan/Projects/cpp/multithreading/tmp.c;0
|
||||
|
||||
[build-menu]
|
||||
CFT_00_LB=_Скомпилировать
|
||||
CFT_00_CM=gcc -g -lpthread -Wall -c "%f"
|
||||
CFT_00_WD=
|
||||
CFT_01_LB=_Сборка
|
||||
CFT_01_CM=gcc -g -lpthread -Wall -o "%e" "%f"
|
||||
CFT_01_WD=
|
||||
filetypes=C;C++;
|
||||
EX_00_LB=_Выполнить
|
||||
EX_00_CM="./%e"
|
||||
EX_00_WD=%d
|
||||
EX_01_LB=run
|
||||
EX_01_CM=
|
||||
EX_01_WD=%d
|
||||
C++FT_01_LB=_Сборка
|
||||
C++FT_01_CM=g++ -lpthread -Wall -o "%e" "%f"
|
||||
C++FT_01_WD=
|
Binary file not shown.
|
@ -0,0 +1,48 @@
|
|||
/* Программа 08-1a.c для иллюстрации работы с
|
||||
семафорами */
|
||||
/* Эта программа получает доступ к одному системному семафору,
|
||||
ждет, пока его значение не станет больше или равным 1
|
||||
после запусков программы 08-1b.c,а затем уменьшает его на 1*/
|
||||
#include <sys/types.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/sem.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
int main()
|
||||
{
|
||||
int semid; /* IPC дескриптор для массива IPC
|
||||
семафоров */
|
||||
char pathname[] = "sem08-1a.c"; /* Имя файла,
|
||||
использующееся для генерации ключа. Файл с таким
|
||||
именем должен существовать в текущей директории */
|
||||
key_t key; /* IPC ключ */
|
||||
struct sembuf mybuf; /* Структура для задания
|
||||
операции над семафором */
|
||||
/* Генерируем IPC-ключ из имени файла 08-1a.c в текущей
|
||||
директории и номера экземпляра массива семафоров 0 */
|
||||
if((key = ftok(pathname,0)) < 0){
|
||||
printf("Can\'t generate key\n");
|
||||
exit(-1);
|
||||
}
|
||||
/* Пытаемся получить доступ по ключу к массиву
|
||||
семафоров, если он существует, или создать его из одного
|
||||
семафора, если его еще не существует, с правами доступа
|
||||
read & write для всех пользователей */
|
||||
if((semid = semget(key, 1, 0666 | IPC_CREAT)) < 0){
|
||||
printf("Can\'t get semid\n");
|
||||
exit(-1);
|
||||
}
|
||||
/* Выполним операцию D(semid1,1) для нашего массива
|
||||
семафоров. Для этого сначала заполним нашу структуру.
|
||||
Флаг, как обычно, полагаем равным 0. Наш массив семафоров
|
||||
состоит из одного семафора с номером 0. Код операции -1.*/
|
||||
mybuf.sem_op = -1;
|
||||
mybuf.sem_flg = 0;
|
||||
mybuf.sem_num = 0;
|
||||
if(semop(semid, &mybuf, 1) < 0){
|
||||
printf("Can\'t wait for condition\n");
|
||||
exit(-1);
|
||||
}
|
||||
printf("Condition is present\n");
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
/* Программа 08-1b.c для иллюстрации работы с
|
||||
семафорами */
|
||||
/* Эта программа получает доступ к одному системному семафору
|
||||
и увеличивает его на 1*/
|
||||
#include <sys/types.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/sem.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
int main()
|
||||
{
|
||||
int semid; /* IPC дескриптор для массива IPC
|
||||
семафоров */
|
||||
char pathname[] = "sem08-1a.c"; /* Имя файла,
|
||||
использующееся для генерации ключа. Файл с таким
|
||||
именем должен существовать в текущей директории */
|
||||
key_t key; /* IPC ключ */
|
||||
struct sembuf mybuf; /* Структура для задания операции
|
||||
над семафором */
|
||||
/* Генерируем IPC ключ из имени файла 08-1a.c в текущей
|
||||
директории и номера экземпляра массива семафоров 0 */
|
||||
if((key = ftok(pathname,0)) < 0){
|
||||
printf("Can\'t generate key\n");
|
||||
exit(-1);
|
||||
}
|
||||
/* Пытаемся получить доступ по ключу к массиву
|
||||
семафоров, если он существует, или создать его из
|
||||
одного семафора, если его еще не существует, с правами доступа
|
||||
read & write для всех пользователей */
|
||||
if((semid = semget(key, 1, 0666 | IPC_CREAT)) < 0){
|
||||
printf("Can\'t get semid\n");
|
||||
exit(-1);
|
||||
}
|
||||
/* Выполним операцию A(semid1,1) для нашего массива
|
||||
семафоров. Для этого сначала заполним нашу структуру.
|
||||
Флаг, как обычно, полагаем равным 0. Наш массив
|
||||
семафоров состоит из одного семафора с номером 0.
|
||||
Код операции 1.*/
|
||||
mybuf.sem_op = 1;
|
||||
mybuf.sem_flg = 0;
|
||||
mybuf.sem_num = 0;
|
||||
if(semop(semid, &mybuf, 1) < 0){
|
||||
printf("Can\'t wait for condition\n");
|
||||
exit(-1);
|
||||
}
|
||||
printf("Condition is set\n");
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
/* semabinit.c - initialize a semaphore for use by programs sema and semb */
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/sem.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
/* The semaphore key is an arbitrary long integer which serves as an
|
||||
external identifier by which the semaphore is known to any program
|
||||
that wishes to use it. */
|
||||
|
||||
#define KEY (1492)
|
||||
|
||||
int main()
|
||||
{
|
||||
int id; /* Number by which the semaphore is known within a program */
|
||||
|
||||
/* The next thing is an argument to the semctl() function. Semctl()
|
||||
does various things to the semaphore depending on which arguments
|
||||
are passed. We will use it to make sure that the value of the
|
||||
semaphore is initially 0. */
|
||||
|
||||
union semun {
|
||||
int val;
|
||||
struct semid_ds *buf;
|
||||
ushort * array;
|
||||
} argument;
|
||||
|
||||
argument.val = 0;
|
||||
|
||||
/* Create the semaphore with external key KEY if it doesn't already
|
||||
exists. Give permissions to the world. */
|
||||
|
||||
id = semget(KEY, 1, 0666 | IPC_CREAT);
|
||||
|
||||
/* Always check system returns. */
|
||||
|
||||
if(id < 0)
|
||||
{
|
||||
fprintf(stderr, "Unable to obtain semaphore.\n");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/* What we actually get is an array of semaphores. The second
|
||||
argument to semget() was the array dimension - in our case
|
||||
1. */
|
||||
|
||||
/* Set the value of the number 0 semaphore in semaphore array
|
||||
# id to the value 0. */
|
||||
|
||||
if( semctl(id, 0, SETVAL, argument) < 0)
|
||||
{
|
||||
fprintf( stderr, "Cannot set semaphore value.\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "Semaphore %d initialized.\n", KEY);
|
||||
}
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
//~ int i = 0;
|
||||
//~ for ( i = 0; i < 10; i++ )
|
||||
//~ {
|
||||
//~ printf("%llu \n", (unsigned long long)time(NULL));
|
||||
//~ sleep(1);
|
||||
//~ }
|
||||
|
||||
printf("sizeof(ssize_t) = %lu\n", sizeof(ssize_t));
|
||||
|
||||
time_t now;
|
||||
struct tm *ts;
|
||||
char buf[80];
|
||||
|
||||
/* Get the current time */
|
||||
now = time(NULL);
|
||||
|
||||
/* Format and print the time, "ddd yyyy-mm-dd hh:mm:ss zzz" */
|
||||
ts = localtime(&now);
|
||||
strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts);
|
||||
printf("%s\n", buf);
|
||||
|
||||
return 0;
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1,12 @@
|
|||
#include <sys/types.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/sem.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
|
||||
printf("sizeof(key_t) = %lu\n", sizeof(key_t));
|
||||
//~ printf("SEMMSL = %lu\n", SEMMSL);
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
volatile int is = 1;
|
||||
|
||||
void sig_int(int sig_no)
|
||||
{
|
||||
is = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
int main()
|
||||
{ int sock, len;
|
||||
struct sockaddr_in addr;
|
||||
char buff[256];
|
||||
|
||||
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
|
||||
{
|
||||
fprintf(stderr, "%d ", errno);
|
||||
perror("socket()");
|
||||
return 1;
|
||||
}
|
||||
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = INADDR_ANY;
|
||||
addr.sin_port = htons(10000);
|
||||
|
||||
signal(SIGINT, sig_int);
|
||||
|
||||
if (bind(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) == -1)
|
||||
{
|
||||
fprintf(stderr, "%d ", errno);
|
||||
perror("bind()");
|
||||
}
|
||||
|
||||
while(is)
|
||||
{ memset(buff, 0, 256);
|
||||
len = sizeof(struct sockaddr_in);
|
||||
memset(&addr, 0, sizeof(struct sockaddr_in));
|
||||
if (recvfrom(sock, buff, 255, 0, (struct sockaddr*)&addr, &len) == -1)
|
||||
{
|
||||
fprintf(stderr, "%d ", errno);
|
||||
perror("recvfrom()");
|
||||
}
|
||||
addr.sin_addr.s_addr = htonl(addr.sin_addr.s_addr);
|
||||
addr.sin_port = htons(addr.sin_port);
|
||||
printf("%d.%d.%d.%d:%d (%d) > %s\n", (addr.sin_addr.s_addr >> 24),
|
||||
((addr.sin_addr.s_addr >> 16) & 0xff),
|
||||
((addr.sin_addr.s_addr >> 8) & 0xff),
|
||||
(addr.sin_addr.s_addr & 0xff), addr.sin_port, len, buff);
|
||||
}
|
||||
|
||||
close(sock);
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
unsigned int ip2int(const char * s) {
|
||||
int ip[4];
|
||||
sscanf(s,"%d.%d.%d.%d",ip,ip+1,ip+2,ip+3);
|
||||
return ip[0]<<24|ip[1]<<16|ip[2]<<8|ip[3];
|
||||
}
|
||||
|
||||
int sendall(int s, char *buf, int len, int flags)
|
||||
{
|
||||
int total = 0;
|
||||
int n;
|
||||
|
||||
while(total < len)
|
||||
{
|
||||
n = send(s, buf+total, len-total, flags);
|
||||
if(n == -1) { break; }
|
||||
total += n;
|
||||
}
|
||||
|
||||
return (n==-1 ? -1 : total);
|
||||
}
|
||||
|
||||
char message[] = "Hello there!\n";
|
||||
char buf[sizeof(message)];
|
||||
|
||||
int main()
|
||||
{
|
||||
int sock;
|
||||
struct sockaddr_in addr;
|
||||
|
||||
sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if(sock < 0)
|
||||
{
|
||||
perror("socket");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(3425); // или любой другой порт...
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // (ip2int("192.168.2.1"));
|
||||
if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
|
||||
{
|
||||
perror("connect");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
send(sock, message, sizeof(message), 0);
|
||||
recv(sock, buf, sizeof(message), 0);
|
||||
|
||||
printf("%s\n",buf);
|
||||
close(sock);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
static const char * int2ip(unsigned int ip) {
|
||||
static char s[16];
|
||||
sprintf(s,"%d.%d.%d.%d",ip>>24,ip<<8>>24,ip<<16>>24,ip<<24>>24);
|
||||
return s;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int sock, listener;
|
||||
struct sockaddr_in addr;
|
||||
char buf[1024];
|
||||
int bytes_read;
|
||||
|
||||
listener = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if(listener < 0)
|
||||
{
|
||||
perror("socket");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(3425);
|
||||
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
|
||||
{
|
||||
perror("bind");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
listen(listener, 1);
|
||||
//~ printf("%X\n",addr.sin_addr.s_addr);
|
||||
while(1)
|
||||
{
|
||||
socklen_t n = sizeof(struct sockaddr);
|
||||
sock = accept(listener, (struct sockaddr *)&addr, &n);
|
||||
printf("incoming request from %s\n",int2ip(ntohl(addr.sin_addr.s_addr)));
|
||||
//~ printf("%X\n",addr.sin_addr.s_addr);
|
||||
if(sock < 0)
|
||||
{
|
||||
perror("accept");
|
||||
exit(3);
|
||||
}
|
||||
|
||||
while(1)
|
||||
{
|
||||
bytes_read = recv(sock, buf, 1024, 0);
|
||||
if(bytes_read <= 0) break;
|
||||
send(sock, buf, bytes_read, 0);
|
||||
printf("%s", buf);
|
||||
}
|
||||
|
||||
close(sock);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include <netdb.h>
|
||||
|
||||
static const char * int2ip(unsigned int ip) {
|
||||
static char s[16];
|
||||
sprintf(s,"%d.%d.%d.%d",ip>>24,ip<<8>>24,ip<<16>>24,ip<<24>>24);
|
||||
return s;
|
||||
}
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
if(argc < 2) {
|
||||
perror("need hex ip address");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
unsigned int ip = 0;
|
||||
sscanf(argv[1],"%X",&ip);
|
||||
|
||||
printf("%s\n",int2ip(ip));
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include <netdb.h>
|
||||
|
||||
unsigned int ip2int(const char * s) {
|
||||
int ip[4];
|
||||
sscanf(s,"%d.%d.%d.%d",ip,ip+1,ip+2,ip+3);
|
||||
return ip[0]<<24|ip[1]<<16|ip[2]<<8|ip[3];
|
||||
}
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
if(argc < 2) {
|
||||
perror("need ip address string");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
printf("%X\n",ip2int(argv[1]));
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
#include <stdio.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
//~ domain = AF_UNIX, AF_INET, AF_INET6, AF_IPX
|
||||
//~ type = SOCK_STREAM, SOCK_DGRAM, SOCK_RAW
|
||||
//~ int socket(int domain, int type, int protocol);
|
||||
|
||||
//~ struct sockaddr {
|
||||
//~ unsigned short sa_family; // Семейство адресов, AF_xxx
|
||||
//~ char sa_data[14]; // 14 байтов для хранения адреса
|
||||
//~ };
|
||||
//~ struct sockaddr_in {
|
||||
//~ short int sin_family; // Семейство адресов
|
||||
//~ unsigned short int sin_port; // Номер порта
|
||||
//~ struct in_addr sin_addr; // IP-адрес
|
||||
//~ unsigned char sin_zero[8]; // "Дополнение" до размера структуры sockaddr
|
||||
//~ };
|
||||
//~ struct in_addr {
|
||||
//~ unsigned long s_addr;
|
||||
//~ };
|
||||
//~ htons, htonl, ntohs, ntohl
|
||||
//~ int bind(int sockfd, struct sockaddr *addr, int addrlen);
|
||||
|
||||
//~ int listen(int sockfd, int backlog);
|
||||
//~ int accept(int sockfd, void *addr, int *addrlen);
|
||||
|
||||
// клиент
|
||||
//~ int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);
|
||||
|
||||
//~ int send(int sockfd, const void *msg, int len, int flags);
|
||||
|
||||
// отправка буфера целиком
|
||||
//~ int sendall(int s, char *buf, int len, int flags)
|
||||
//~ {
|
||||
//~ int total = 0;
|
||||
//~ int n;
|
||||
//~
|
||||
//~ while(total < len)
|
||||
//~ {
|
||||
//~ n = send(s, buf+total, len-total, flags);
|
||||
//~ if(n == -1) { break; }
|
||||
//~ total += n;
|
||||
//~ }
|
||||
//~
|
||||
//~ return (n==-1 ? -1 : total);
|
||||
//~ }
|
||||
|
||||
//~ int recv(int sockfd, void *buf, int len, int flags);
|
||||
|
||||
// закрытие соединения
|
||||
//~ int close(int fd);
|
||||
|
||||
// запрет передачи 0 - чтения, 1 - записи, 2 - и того, и др.
|
||||
//~ int shutdown(int sockfd, int how);
|
||||
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
struct a
|
||||
{
|
||||
char aaa[256];
|
||||
};
|
||||
|
||||
printf("%lu\n", sizeof(struct a));
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
#include <stdio.h>
|
||||
|
||||
void f()
|
||||
{
|
||||
int c = 0;
|
||||
printf("c=%lu\n",(unsigned long)&c);
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
//~ printf("%lu\n", sizeof(long));
|
||||
|
||||
int a = 0;
|
||||
|
||||
int pid = fork();
|
||||
printf("pid=%d\n",pid);
|
||||
printf("a=%lu\n",(unsigned long)&a);
|
||||
|
||||
int b = 0;
|
||||
printf("b=%lu\n",(unsigned long)&b);
|
||||
|
||||
f();
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
// Filename : string_wstring.cpp
|
||||
// Author : A.G.Raja
|
||||
// License : GPL
|
||||
// Website : http://agraja.wordpress.com
|
||||
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
string wstring2string(wstring wstr) {
|
||||
string str(wstr.length(),' ');
|
||||
copy(wstr.begin(),wstr.end(),str.begin());
|
||||
return str;
|
||||
}
|
||||
|
||||
wstring string2wstring(string str) {
|
||||
wstring wstr(str.length(),L' ');
|
||||
copy(str.begin(),str.end(),wstr.begin());
|
||||
return wstr;
|
||||
}
|
||||
|
||||
int main() {
|
||||
wstring wstr = string2wstring("raja");
|
||||
string str = wstring2string(wstr);
|
||||
cout<<str<<endl;
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
gcc `pkg-config --cflags --libs gtk+-2.0` hello_world.c -o hello_world
|
Binary file not shown.
|
@ -0,0 +1,25 @@
|
|||
/* Подключаем библиотеку GTK+ */
|
||||
# include <gtk/gtk.h>
|
||||
int main( int argc, char *argv[])
|
||||
{
|
||||
/* Объявляем виджеты */
|
||||
GtkWidget *label; // Метка
|
||||
GtkWidget *window; // Главное окно
|
||||
/* Инициализируем GTK+ */
|
||||
gtk_init(&argc, &argv);
|
||||
/* Создаем главное окно */
|
||||
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
|
||||
/* Устанавливаем заголовок окна "Здравствуй, мир!" */
|
||||
gtk_window_set_title(GTK_WINDOW(window), "Здравствуй, мир!");
|
||||
/* Создаем метку с текстом "Здравствуй, мир!" */
|
||||
label = gtk_label_new("Здравствуй, мир!");
|
||||
/* Вставляем метку в главное окно */
|
||||
gtk_container_add(GTK_CONTAINER(window), label);
|
||||
/* Показываем окно вместе с виджетами */
|
||||
gtk_widget_show_all(window);
|
||||
/* Соединяем сигнал завершения с выходом из программы */
|
||||
g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
|
||||
/* Приложение переходит в вечный цикл ожидания действий пользователя */
|
||||
gtk_main();
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path=""/>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
|
||||
<classpathentry kind="output" path=""/>
|
||||
</classpath>
|
|
@ -0,0 +1,17 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>helloworld1</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
Binary file not shown.
|
@ -0,0 +1,6 @@
|
|||
import java.util.*;
|
||||
public class hello {
|
||||
public static void main(String[] args) {
|
||||
System.out.print("Hello, world!");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
|
||||
BITS 32
|
||||
|
||||
GLOBAL divover
|
||||
|
||||
SECTION .text
|
||||
|
||||
mem dd 01h
|
||||
|
||||
divover:
|
||||
|
||||
mov eax, [esp+4]
|
||||
mov ecx, [esp+8]
|
||||
|
||||
mov ebx, mem
|
||||
mov [ebx], ecx
|
||||
|
||||
div ebx
|
||||
ret
|
||||
|
||||
; mov eax, [esp+4] ; n в eax
|
||||
; cmp eax, 1
|
||||
; je ret1 ; 1 ! = 1
|
||||
;
|
||||
; push ecx ; save used ecx
|
||||
;
|
||||
; dec eax ; eax = n-1
|
||||
; push eax
|
||||
; call fact ; в eax (n-1)!
|
||||
; pop ecx ; ecx = n
|
||||
; inc ecx
|
||||
; mul ecx ; eax *= ecx
|
||||
;
|
||||
; pop ecx ; restore used ecx
|
||||
;
|
||||
;ret1:
|
||||
; ret
|
|
@ -0,0 +1,16 @@
|
|||
|
||||
#include <stdio.h>
|
||||
|
||||
typedef unsigned int T;
|
||||
|
||||
extern T divover(T m, T n);
|
||||
|
||||
int main ( int argc, char * argv[] ) {
|
||||
|
||||
T m = atoi(argv[1]), n = atoi(argv[2]);
|
||||
|
||||
printf ( "Остаток от деления %d на %d равен %d", m, n, divover(m,n));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
Binary file not shown.
|
@ -0,0 +1,13 @@
|
|||
#!/bin/sh
|
||||
|
||||
target=2
|
||||
|
||||
rm -f $target
|
||||
nasm -f elf ${target}.asm
|
||||
gcc -o ${target} ${target}.c ${target}.o
|
||||
for m in 1 2 3 4 5 6 7 8 9 10 11 12 ; do
|
||||
for n in 1 2 3 4 5 6 7 8 9 10 11 12 ; do
|
||||
echo "divover($m/$n) = `./${target} $m $n`"
|
||||
done
|
||||
done
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue