Compare commits

..

2 Commits

Author SHA1 Message Date
f2b20118e0
update C snipplets 2024-04-27 23:54:46 +03:00
42d18ccae1
update .editorconfig
added Ruby
fix Solar2D path
ignore `haarcascade_frontalface_default.xml` file
2024-04-27 23:21:58 +03:00
60 changed files with 599 additions and 833 deletions

View File

@ -20,6 +20,11 @@ indent_size = 4
indent_style = space indent_style = space
indent_size = 4 indent_size = 4
# Ruby
[*.rb]
indent_style = space
indent_size = 2
# Crystal # Crystal
[{*.cr,shards.yml}] [{*.cr,shards.yml}]
indent_style = space indent_style = space
@ -85,13 +90,16 @@ indent_size = 4
indent_style = tab indent_style = tab
indent_size = 4 indent_size = 4
[snipplets/code/Gambas/*] [code/Gambas/*]
indent_size = 2 indent_size = 2
[snipplets/projects/Solar2D**] [projects/Solar2D/**]
indent_style = unset indent_style = unset
indent_size = unset indent_size = unset
end_of_line = unset end_of_line = unset
charset = unset charset = unset
trim_trailing_whitespace = unset trim_trailing_whitespace = unset
insert_final_newline = unset insert_final_newline = unset
[projects/CV/haarcascade_frontalface_default.xml]
indent_size = unset

View File

@ -9,30 +9,29 @@
char message[] = "Hello there!\n"; char message[] = "Hello there!\n";
char buf[sizeof(message)]; char buf[sizeof(message)];
int main() int main() {
{ int sock;
int sock; struct sockaddr_in addr;
struct sockaddr_in addr;
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) { if (sock < 0) {
perror("socket"); perror("socket");
exit(1); exit(1);
} }
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
addr.sin_port = htons(3425); // или любой другой порт... addr.sin_port = htons(3425); // или любой другой порт...
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("connect"); perror("connect");
exit(2); exit(2);
} }
send(sock, message, sizeof(message), 0); send(sock, message, sizeof(message), 0);
recv(sock, buf, sizeof(message), 0); recv(sock, buf, sizeof(message), 0);
printf(buf); printf(buf);
close(sock); close(sock);
return 0; return 0;
} }

View File

@ -5,44 +5,44 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <netinet/in.h> #include <netinet/in.h>
int main() int main() {
{ int sock, listener;
int sock, listener; struct sockaddr_in addr;
struct sockaddr_in addr; char buf[1024];
char buf[1024]; int bytes_read;
int bytes_read;
listener = socket(AF_INET, SOCK_STREAM, 0); listener = socket(AF_INET, SOCK_STREAM, 0);
if (listener < 0) { if (listener < 0) {
perror("socket"); perror("socket");
exit(1); 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);
while (1) {
sock = accept(listener, NULL, NULL);
if (sock < 0) {
perror("accept");
exit(3);
} }
addr.sin_family = AF_INET; while (1) {
addr.sin_port = htons(3425); bytes_read = recv(sock, buf, 1024, 0);
addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bytes_read <= 0)
if (bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0) { break;
perror("bind"); send(sock, buf, bytes_read, 0);
exit(2);
} }
listen(listener, 1); close(sock);
}
while(1) { return 0;
sock = accept(listener, NULL, NULL);
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);
}
close(sock);
}
return 0;
} }

View File

@ -0,0 +1,31 @@
#include <stdio.h> // file handling functions
#include <stdlib.h> // atoi
#include <string.h> // strtok
int main() {
char buffer[80];
FILE *stream = fopen("example.csv", "r");
while (fgets(buffer, 80, stream)) {
char *token = strtok(buffer, ",");
// If you only need the first column of each row
// Если нам нужен только первый столбец каждой строки
if (token) {
int n = atoi(token);
printf("%s\n", n);
}
// If you need all the values in a row
// Если нам нужны все значения подряд
while (token) {
// Just printing each integer here but handle as needed
// int n = atoi(token);
printf("%s\n", token);
token = strtok(NULL, ",");
}
}
return 0;
}

View File

@ -1,13 +1,43 @@
# C # C
## Other ## Работа со строками
- [seconds_to_minutes_and_hours.c](seconds_to_minutes_and_hours.c) - Преобразование секунд в минуты и часы - [clear_string.c](Strings/clear_string.c) - Очистка строки `char *`
- [get_ram_usage.c](get_ram_usage.c) - Получение используемой приложением RAM - [`strlen()`](Strings/buffer_len.h) - Получить длину строки
## SQLite 3 - []() -
- [CREATE TABLE](sqlite/sqlite3_create.c) ## Преобразования
- [INSERT INTO](sqlite/sqlite3_insert.c)
- [SELECT](sqlite/sqlite3_select.c) - [rgbToHex.c](Transform/rgbToHex.c) - Преобразование RGB строки в HEX строку _(#008040)_
- [UPDATE](sqlite/sqlite3_update.c) - [seconds_to_minutes_and_hours.c](Transform/seconds_to_minutes_and_hours.c) - Преобразование секунд в минуты и часы
- [DELETE](sqlite/sqlite3_delete.c)
## Парсеры
- [read_csv.c](Parsing/CSV/read_csv.c) - Парсинг CSV файлов
## Система
- [get_ram_usage.c](System/get_ram_usage.c) - Получение статистики использования RAM
- [`sys/statvfs.h`](System/disk_usage.c) - Получение статиистики использования диска
- [`pidof`](System/get-pid-by-process-name.c) - Получение ID процесса по его имени
## 🗄️ SQLite 3
- [CREATE TABLE](SQLite/sqlite3_create.c) — Создание таблицы
- [INSERT INTO](SQLite/sqlite3_insert.c) — Вставка
- [SELECT](SQLite/sqlite3_select.c) — Выбор
- [UPDATE](SQLite/sqlite3_update.c) — Обновление
- [DELETE](SQLite/sqlite3_delete.c) — Удаление
## Web
- [`webui`](Web/webui) - Пример библиотеки [webui](https://webui.me/)
- [`ulfius`](Web/ulfius-server) - Пример библиотеки ulfius
## Другое
- [`conio.h`](conio.h/README.md) - Описание и работа функций заголовоного файла `conio.h`.
- [unixsocket](unixsocket) - Пример работы с сокетами UNIX
- [AF_INET_sockets](AF_INET_sockets) - Пример работы с сокетами
- [atomic.c](atomic.c) - Пример `atomic`
- [thread.c](thread.c) - Пример многопоточности

1
code/C/SQLite/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
sqlite3_*

View File

@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for (i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char *argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return (0);
} else {
fprintf(stdout, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "CREATE TABLE COMPANY("
"ID INT PRIMARY KEY NOT NULL,"
"NAME TEXT NOT NULL,"
"AGE INT NOT NULL,"
"ADDRESS CHAR(50),"
"SALARY REAL);";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Table created successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -0,0 +1,51 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char *)data);
for (i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char *argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char *data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return (0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create merged SQL statement */
sql = "DELETE from COMPANY where ID=2; "
"SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void *)data, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for (i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char *argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return (0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
"VALUES (1, 'Paul', 32, 'California', 20000.00 ); "
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); "
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)"
"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );"
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)"
"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00);";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Records created successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -0,0 +1,50 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char *)data);
for (i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char *argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char *data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return (0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void *)data, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -0,0 +1,51 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char *)data);
for (i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char *argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char *data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return (0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create merged SQL statement */
sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; "
"SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void *)data, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -0,0 +1,9 @@
int main(int argc, char const *argv[]) {
char *buffer = malloc(256 + 1);
buffer[0] = '\0';
strcpy(buffer, "");
memset(buffer, '\0', sizeof(buffer));
return 0;
}

View File

@ -0,0 +1,12 @@
pid_t getPIDbyName(char *ps_name) {
FILE *fp;
char *cmd = (char *)calloc(1, 200);
sprintf(cmd, "pidof %s", ps_name);
fp = popen(cmd, "r");
fread(cmd, 1, 200, fp);
fclose(fp);
return atoi(cmd);
}

View File

@ -0,0 +1,11 @@
#include <stdio.h>
int main(int argc, char const *argv[]) {
int red = 0;
int green = 128;
int blue = 64;
printf("#%.2x%.2x%.2x\n", red, green, blue); // #008040
return 0;
}

View File

Before

Width:  |  Height:  |  Size: 78 KiB

After

Width:  |  Height:  |  Size: 78 KiB

View File

@ -5,26 +5,24 @@
atomic_int acnt; atomic_int acnt;
int cnt; int cnt;
int f(void* thr_data) int f(void *thr_data) {
{ (void)thr_data;
(void)thr_data; for (int n = 0; n < 1000; ++n) {
for(int n = 0; n < 1000; ++n) { ++cnt;
++cnt; ++acnt;
++acnt; // for this example, relaxed memory order is sufficient, e.g.
// for this example, relaxed memory order is sufficient, e.g. // atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed);
// atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed); }
} return 0;
return 0;
} }
int main(void) int main(void) {
{ thrd_t thr[10];
thrd_t thr[10]; for (int n = 0; n < 10; ++n)
for(int n = 0; n < 10; ++n) thrd_create(&thr[n], f, NULL);
thrd_create(&thr[n], f, NULL); for (int n = 0; n < 10; ++n)
for(int n = 0; n < 10; ++n) thrd_join(thr[n], NULL);
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt); printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt); printf("The non-atomic counter is %u\n", cnt);
} }

View File

@ -1,10 +0,0 @@
int main(int argc, char const *argv[])
{
char *buffer = malloc(256 + 1);
buffer[0] = '\0';
strcpy(buffer, "");
memset(buffer, '\0', sizeof(buffer));
return 0;
}

View File

@ -1,10 +0,0 @@
#!/bin/sh
files=(
"file.c"
)
for file in "${files[@]}"
do
clang-format -i --style=LLVM --sort-includes=false $file
done

View File

@ -1,6 +0,0 @@
[{clear,build,format-code}]
indent_style = space
indent_size = 4
[{*.c,*.ino}]
indent_size = 2

View File

@ -1,12 +0,0 @@
# libserialport examples
port_info.c
list_ports.c
send_receive.c
# binaries
port_info
list_ports
send_receive
listen
abc.txt

View File

@ -1 +0,0 @@
3party/

View File

@ -1,24 +0,0 @@
/*
Author: Alexander Popov
License: Unlicense
*/
#include "3party/AsyncStream.h"
AsyncStream<50> serial(&Serial, '\n');
void setup() {
Serial.begin(9600);
}
void loop() {
if (strcmp(serial.buf, "ping") == 0) {
Serial.println("PONG");
}
Serial.println("ooooo");
// delay(1000);
Serial.println("zzzz");
// delay(1000);
Serial.println("xxx");
// delay(1000);
}

View File

@ -1,3 +0,0 @@
Download `AsyncStream.h` from
https://github.com/GyverLibs/AsyncStream
and drop in to `3party` folder.

View File

@ -1,18 +0,0 @@
Download `libserialport` library.
```sh
git clone git://sigrok.org/libserialport
```
For **build** code use `build` script or build files manually.
Example:
```sh
export C_INCLUDE_PATH=<path/to/libserialport>
export LIBRARY_PATH=<path/to/libserialport/.libs>
gcc -static -Wall -O3 -o <output_filename> <file.c> -lserialport
```
Arduino example project store in `Board` folder.

View File

@ -1,20 +0,0 @@
#!/bin/sh
#
# build - script for build all files.
#
# Alexander Popov <iiiypuk@fastmail.fm>
export C_INCLUDE_PATH=$HOME/Git/libserialport
export LIBRARY_PATH=$HOME/Git/libserialport/.libs
for file in \
port_info.c \
list_ports.c \
send_receive.c \
listen.c \
do
echo -ne "[ ] Building $file...\r"
gcc -static -Wall -O3 -o ${file%.*} $file -lserialport
echo [OK
done

View File

@ -1,20 +0,0 @@
#!/bin/sh
#
# build - script for build all files.
#
# Alexander Popov <iiiypuk@fastmail.fm>
export C_INCLUDE_PATH=$HOME/Git/libserialport
export LIBRARY_PATH=$HOME/Git/libserialport/.libs
for file in \
port_info.c \
list_ports.c \
send_receive.c \
listen.c \
do
echo -ne "[ ] Building $file...\r"
tcc -Wall -O3 -o ${file%.*} -I$C_INCLUDE_PATH $file $LIBRARY_PATH/libserialport.a
echo [OK
done

View File

@ -1,17 +0,0 @@
#!/bin/sh
#
# clear - script for delete all builded files.
#
# Alexander Popov <iiiypuk@fastmail.fm>
files=(
"port_info"
"list_ports"
"send_receive"
"listen"
)
for file in ${files[@]}
do
rm $file &> /dev/null
done

View File

@ -1,14 +0,0 @@
#!/bin/sh
#
# formt-code - script for beautify code by clang-format.
#
# Alexander Popov <iiiypuk@fastmail.fm>
files=(
"listen.c"
)
for file in "${files[@]}"
do
clang-format -i --style=LLVM --sort-includes=false $file
done

View File

@ -1,133 +0,0 @@
#include <libserialport.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <signal.h>
/* Helper function for error handling. */
int check(enum sp_return result);
void handle_sigint(int sig);
bool INTERRUPT = false;
int main(int argc, char **argv) {
struct sp_port *serial_port;
char *port_name;
const int size = 256;
char *buffer = malloc(size + 1);
const unsigned int timeout = 1000;
int result;
/* Get the port name from the command line. */
if (argc != 2) {
printf("Usage: %s <port>\n\n", argv[0]);
struct sp_port **port_list;
enum sp_return result = sp_list_ports(&port_list);
/* Getting the available ports. */
if (result != SP_OK) {
puts("Getting available ports failed!");
} else {
puts("Available ports:");
int i;
for (i = 0; port_list[i] != NULL; i++) {
/* Get the name of the port. */
struct sp_port *port = port_list[i];
char *port_name = sp_get_port_name(port);
printf(" * %s\n", port_name);
}
printf("\nAvailable %d ports.\n", i);
sp_free_port_list(port_list);
}
return -1;
} else {
port_name = argv[1];
}
printf("Connecting to '%s'...\n", port_name);
check(sp_get_port_by_name(port_name, &serial_port));
check(sp_open(serial_port, SP_MODE_READ_WRITE));
check(sp_set_baudrate(serial_port, 9600));
check(sp_set_bits(serial_port, 8));
check(sp_set_parity(serial_port, SP_PARITY_NONE));
check(sp_set_stopbits(serial_port, 1));
check(sp_set_flowcontrol(serial_port, SP_FLOWCONTROL_NONE));
puts("Connected.");
signal(SIGINT, handle_sigint);
FILE *output_file;
output_file = fopen("./abc.txt", "w");
/* Reading lines from serial port. */
bool reading = true;
while (reading && !INTERRUPT) {
int pos = 0;
/* Character-by-character reading. */
while (pos < size) {
result = check(sp_blocking_read(serial_port, buffer + pos, 1, timeout));
if (result == -1) {
puts("Error reading from serial port");
reading = false;
break;
} else if (result == 0) {
puts("No more data");
break;
} else {
if (buffer[pos] == '\n') {
buffer[pos] = '\0';
break;
}
pos++;
}
}
puts(buffer);
fputs(buffer, output_file);
}
fclose(output_file);
free(buffer);
return 0;
}
/* Helper function for error handling. */
int check(enum sp_return result) {
char *error_message;
switch (result) {
case SP_ERR_ARG:
puts("Error: Invalid argument.");
abort();
case SP_ERR_FAIL:
error_message = sp_last_error_message();
printf("Error: Failed: %s\n", error_message);
sp_free_error_message(error_message);
abort();
case SP_ERR_SUPP:
puts("Error: Not supported.");
abort();
case SP_ERR_MEM:
puts("Error: Couldn't allocate memory.");
abort();
case SP_OK:
default:
return result;
}
}
void handle_sigint(int sig) { INTERRUPT = true; }

View File

@ -1,31 +0,0 @@
#include <stdio.h> // file handling functions
#include <stdlib.h> // atoi
#include <string.h> // strtok
int main() {
char buffer[80];
FILE *stream = fopen("example.csv", "r");
while (fgets(buffer, 80, stream)) {
char *token = strtok(buffer, ",");
// If you only need the first column of each row
// Если нам нужен только первый столбец каждой строки
if (token) {
int n = atoi(token);
printf("%s\n", n);
}
// If you need all the values in a row
// Если нам нужны все значения подряд
while (token) {
// Just printing each integer here but handle as needed
// int n = atoi(token);
printf("%s\n", token);
token = strtok(NULL, ",");
}
}
return 0;
}

View File

@ -1,12 +0,0 @@
#include <stdio.h>
int main(int argc, char const *argv[])
{
int red = 0;
int green = 128;
int blue = 64;
printf("#%.2x%.2x%.2x\n", red, green, blue); //#008040
return 0;
}

View File

@ -1,52 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stdout, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "CREATE TABLE COMPANY(" \
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"AGE INT NOT NULL," \
"ADDRESS CHAR(50)," \
"SALARY REAL);";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Table created successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -1,51 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char*)data);
for (i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create merged SQL statement */
sql = "DELETE from COMPANY where ID=2; " \
"SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -1,55 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for (i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \
"VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \
"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00);";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Records created successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -1,50 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char*)data);
for (i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -1,51 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create merged SQL statement */
sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \
"SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}

View File

@ -8,24 +8,24 @@
int g = 0; int g = 0;
void *my_thread(void *vargp) { void *my_thread(void *vargp) {
int *id = (int *)vargp; int *id = (int *)vargp;
static int s = 0; static int s = 0;
++s; ++s;
++g; ++g;
printf("Thread ID: %d, Static: %d, Global: %d\n", *id, ++s, ++g); printf("Thread ID: %d, Static: %d, Global: %d\n", *id, ++s, ++g);
} }
int main() { int main() {
pthread_t tid; pthread_t tid;
int i; int i;
for (i = 0; i < 3; i++) for (i = 0; i < 3; i++)
pthread_create(&tid, NULL, my_thread, (void *)&tid); pthread_create(&tid, NULL, my_thread, (void *)&tid);
pthread_exit(NULL); pthread_exit(NULL);
return 0; return 0;
} }

Binary file not shown.

Binary file not shown.

View File

@ -12,68 +12,67 @@
#include <unistd.h> #include <unistd.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
struct sockaddr_un addr; struct sockaddr_un addr;
int i; int i;
int ret; int ret;
int data_socket; int data_socket;
char buffer[BUFFER_SIZE]; char buffer[BUFFER_SIZE];
/* Create local socket. */ /* Create local socket. */
data_socket = socket(AF_UNIX, SOCK_STREAM, 0); data_socket = socket(AF_UNIX, SOCK_STREAM, 0);
if (data_socket == -1) { if (data_socket == -1) {
perror("socket"); perror("socket");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
/* /*
* For portability clear the whole structure, since some * For portability clear the whole structure, since some
* implementations have additional (nonstandard) fields in * implementations have additional (nonstandard) fields in
* the structure. * the structure.
*/ */
memset(&addr, 0, sizeof(struct sockaddr_un)); memset(&addr, 0, sizeof(struct sockaddr_un));
/* Connect socket to socket address */ /* Connect socket to socket address */
addr.sun_family = AF_UNIX; addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) - 1); strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) - 1);
ret = connect (data_socket, (const struct sockaddr *) &addr, ret = connect(data_socket, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un));
sizeof(struct sockaddr_un)); if (ret == -1) {
fprintf(stderr, "The server is down.\n");
exit(EXIT_FAILURE);
}
/* Send arguments. */
for (i = 1; i < argc; ++i) {
ret = write(data_socket, argv[i], strlen(argv[i]) + 1);
if (ret == -1) { if (ret == -1) {
fprintf(stderr, "The server is down.\n"); perror("write");
exit(EXIT_FAILURE); break;
} }
}
/* Send arguments. */ /* Request result. */
for (i = 1; i < argc; ++i) { strcpy(buffer, "END");
ret = write(data_socket, argv[i], strlen(argv[i]) + 1); ret = write(data_socket, buffer, strlen(buffer) + 1);
if (ret == -1) { if (ret == -1) {
perror("write"); perror("write");
break; exit(EXIT_FAILURE);
} }
}
/* Request result. */ /* Receive result. */
strcpy (buffer, "END"); ret = read(data_socket, buffer, BUFFER_SIZE);
ret = write(data_socket, buffer, strlen(buffer) + 1); if (ret == -1) {
if (ret == -1) { perror("read");
perror("write"); exit(EXIT_FAILURE);
exit(EXIT_FAILURE); }
}
/* Receive result. */ /* Ensure buffer is 0-terminated. */
ret = read(data_socket, buffer, BUFFER_SIZE); buffer[BUFFER_SIZE - 1] = 0;
if (ret == -1) {
perror("read");
exit(EXIT_FAILURE);
}
/* Ensure buffer is 0-terminated. */ printf("Result = %s\n", buffer);
buffer[BUFFER_SIZE - 1] = 0;
printf("Result = %s\n", buffer); /* Close socket. */
close(data_socket);
/* Close socket. */ exit(EXIT_SUCCESS);
close(data_socket);
exit(EXIT_SUCCESS);
} }

Binary file not shown.

View File

@ -11,113 +11,112 @@
#include <unistd.h> #include <unistd.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
struct sockaddr_un addr; struct sockaddr_un addr;
int down_flag = 0; int down_flag = 0;
int ret; int ret;
int listen_socket; int listen_socket;
int data_socket; int data_socket;
int result; int result;
char buffer[BUFFER_SIZE]; char buffer[BUFFER_SIZE];
/* /*
* In case the program exited inadvertently on the last run, * In case the program exited inadvertently on the last run,
* remove the socket. * remove the socket.
*/ */
unlink(SOCKET_NAME); unlink(SOCKET_NAME);
/* Create local socket. */ /* Create local socket. */
listen_socket = socket(AF_UNIX, SOCK_STREAM, 0); listen_socket = socket(AF_UNIX, SOCK_STREAM, 0);
if (listen_socket == -1) { if (listen_socket == -1) {
perror("socket"); perror("socket");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
}
/*
* For portability clear the whole structure, since some
* implementations have additional (nonstandard) fields in
* the structure.
*/
memset(&addr, 0, sizeof(struct sockaddr_un));
/* Bind socket to socket name. */
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) - 1);
ret = bind(listen_socket, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un));
if (ret == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
/*
* Prepare for accepting connections. The backlog size is set
* to 20. So while one request is being processed other requests
* can be waiting.
*/
ret = listen(listen_socket, 20);
if (ret == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
/* This is the main loop for handling connections. */
for (;;) {
/* Wait for incoming connection. */
data_socket = accept(listen_socket, NULL, NULL);
if (data_socket == -1) {
perror("accept");
exit(EXIT_FAILURE);
} }
/* result = 0;
* For portability clear the whole structure, since some
* implementations have additional (nonstandard) fields in
* the structure.
*/
memset(&addr, 0, sizeof(struct sockaddr_un));
/* Bind socket to socket name. */
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) - 1);
ret = bind(listen_socket, (const struct sockaddr *) &addr,
sizeof(struct sockaddr_un));
if (ret == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
/*
* Prepare for accepting connections. The backlog size is set
* to 20. So while one request is being processed other requests
* can be waiting.
*/
ret = listen(listen_socket, 20);
if (ret == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
/* This is the main loop for handling connections. */
for (;;) { for (;;) {
/* Wait for incoming connection. */ /* Wait for next data packet. */
data_socket = accept(listen_socket, NULL, NULL); ret = read(data_socket, buffer, BUFFER_SIZE);
if (data_socket == -1) { if (ret == -1) {
perror("accept"); perror("read");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
result = 0; /* Ensure buffer is 0-terminated. */
for(;;) { buffer[BUFFER_SIZE - 1] = 0;
/* Wait for next data packet. */
ret = read(data_socket, buffer, BUFFER_SIZE);
if (ret == -1) {
perror("read");
exit(EXIT_FAILURE);
}
/* Ensure buffer is 0-terminated. */ /* Handle commands. */
buffer[BUFFER_SIZE - 1] = 0; if (!strncmp(buffer, "DOWN", BUFFER_SIZE)) {
down_flag = 1;
break;
}
/* Handle commands. */ if (!strncmp(buffer, "END", BUFFER_SIZE)) {
if (!strncmp(buffer, "DOWN", BUFFER_SIZE)) { break;
down_flag = 1; }
break;
}
if (!strncmp(buffer, "END", BUFFER_SIZE)) { /* Add received summand. */
break; result += atoi(buffer);
}
/* Add received summand. */
result += atoi(buffer);
}
/* Send result. */
sprintf(buffer, "%d", result);
ret = write(data_socket, buffer, BUFFER_SIZE);
if (ret == -1) {
perror("write");
exit(EXIT_FAILURE);
}
/* Close socket. */
close(data_socket);
/* Quit on DOWN command. */
if (down_flag) {
break;
}
} }
close(listen_socket); /* Send result. */
sprintf(buffer, "%d", result);
ret = write(data_socket, buffer, BUFFER_SIZE);
/* Unlink the socket. */ if (ret == -1) {
unlink(SOCKET_NAME); perror("write");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS); /* Close socket. */
close(data_socket);
/* Quit on DOWN command. */
if (down_flag) {
break;
}
}
close(listen_socket);
/* Unlink the socket. */
unlink(SOCKET_NAME);
exit(EXIT_SUCCESS);
} }